【C#】亚马逊S3云存储服务器文件上传笔记

最近需要每天同步内网的数据到外网的服务器上,用了几天CyberDuck觉得经常忘记同步,故研究了一下亚马逊S3的接口,写了个定时上传文件的服务。

附上代码:

        public string UploadFile()
        {
            String accessKeyID = "****";
            String secretKey = "*****";
            String bucketName = "根文件夹名";
            String s3Path = "子文件夹名/文件名";
            
            AWSCredentials credentials;
            credentials = new BasicAWSCredentials(accessKeyID, secretKey);
            AmazonS3Client s3Client = new AmazonS3Client(accessKeyID, secretKey, Amazon.RegionEndpoint.USEast1);
            if (!CheckBucketExists(s3Client, bucketName))
            {
                s3Client.PutBucket(bucketName);
            } 
            string localPath = "本地文件地址";
            PutObjectRequest obj = new PutObjectRequest();
            var fileStream = new FileStream(localPath, FileMode.Open, FileAccess.Read);
            obj.InputStream = fileStream;
            obj.BucketName = bucketName;
            obj.Key = s3Path;
            obj.CannedACL = S3CannedACL.PublicRead;
            // 默认添加public权限
            s3Client.PutObject(obj);
            return “success”;
        }


        public static bool CheckBucketExists (AmazonS3Client s3, String bucketName) {  
            List buckets = s3.ListBuckets().Buckets;
            foreach(S3Bucket bucket in buckets){
                if (bucket.BucketName == bucketName) {  
                    return true;  
                }  
            }
            return false;  
        }  



你可能感兴趣的:(C#)