在 C# 中管理 AWS S3 对象

AWS 的简单存储服务(简称 S3)提供行业领先的可扩展性、数据可用性、安全性和性能。我们可以使用 S3 存储、检索和管理任意数量的数据,例如网站、移动应用程序、备份等等。

使用代码

在使用此代码之前,需要拥有一个 AWS 账户并知道如何在 AWS 中创建 S3 存储桶。

在 Visual Studio 中启动一个新项目,然后从 Nuget 存储库将 AWS SDK 添加到项目中:

 为了维护对象并执行下载、上传和删除,可以创建单独的类:

S3BucketDelete:删除对象(文件和文件夹)

public class S3BucketDelete
	{
        public string bucketName { get; set; }
        public string fileName { get; set; }
        public string filePath { get; set; }

        public void DeleteFile()
        {
			try
			{
                var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);

                DeleteObjectRequest delRequest = new DeleteObjectRequest
                {
                    BucketName = bucketName,
                    Key = Path.Combine(filePath, fileName)  // Delete file at the path
                };

                DeleteObjectResponse response = client.DeleteObject(delRequest);
            }catch(Exception x)
			{
                MessageBox.Show(x.Message);
			}
        }
        public void DeleteFolder()
        {
            var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);

            DeleteObjectRequest delRequest = new DeleteObjectRequest
            {
                BucketName = bucketName,
                Key = Path.Combine(filePath, fileName) + "/" // Delete folder
            };

            DeleteObjectResponse response = client.DeleteObject(delRequest);
        }


    }

S3BucketDownload:从 AWS S3 将对象下载到本地目的地

public class S3BucketDownload
	{
		public string bucketName { get; set; }
        public string keyName { get; set; }
		public string filePath { get; set; }
		public string fileDestination { get; set; }
        public async Task DownoadFileAsync()
        {
            try
            {
                var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
                var fileTransferUtility = new TransferUtility(client);

                var request = new TransferUtilityDownloadRequest
                {
                    BucketName = bucketName,
                    FilePath = Path.Combine(filePath, keyName),
                  //  Key = Path.Combine(fileDestination, keyName),
                    Key = fileDestination+keyName,
                    //PartSize = 6291456, // 6 MB.
                    //ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
                };

                await fileTransferUtility.DownloadAsync(request);
            }
            catch (AmazonS3Exception s3Exception)
            {
                MessageBox.Show(s3Exception.Message, "Error 102", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error 103", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

S3BucketUpload:将位置源中的文件上传到我们的 S3

public class S3BucketUploader
	{
        public string bucketName { get; set; }
        public string keyName { get; set; }
        public string filePath { get; set; }
        public string fileDestination { get; set; }

        public void UploadFile()
        {
          try
			{
                var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);

                PutObjectRequest putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    FilePath = filePath,
                    ContentType = "text/plain"
                };

                PutObjectResponse response = client.PutObject(putRequest);
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error 101", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void UploadFileToFolder()
        {
			try
			{
                var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);

                PutObjectRequest putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = Path.Combine(fileDestination, keyName),
                    FilePath = filePath,
                    ContentType = "text/plain"
                };

                PutObjectResponse response = client.PutObject(putRequest);
            }catch(Exception x)
			{
                MessageBox.Show(x.Message, "Error 100", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public  async Task UploadFileAsync()
        {
            try
            {
                var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
                var fileTransferUtility = new TransferUtility(client);

                var request = new TransferUtilityUploadRequest
                {
                    BucketName = bucketName,
                    FilePath = filePath,
                    Key = Path.Combine(fileDestination, keyName),
                    PartSize = 6291456, // 6 MB.
                    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256
                };

                await fileTransferUtility.UploadAsync(request);
            }
            catch (AmazonS3Exception s3Exception)
            {
                MessageBox.Show(s3Exception.Message, "Error 102", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error 103", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }
    }

S3BucketView 在 S3 中查看对象(文件和文件夹)

public class S3BucketView
	{
		public string bucketName { get; set; }
		public ListObjectsResponse ListFolders()
		{
			//var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);

			ListObjectsResponse response;
			ListObjectsResponse result ;
			IAmazonS3 client;
			try
			{
				using (client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2))
				{
					ListObjectsRequest listRequest = new ListObjectsRequest
					{
						BucketName = bucketName,
					};
					do
					{
						response = client.ListObjects(listRequest);


						IEnumerable<s3object> folders = response.S3Objects.Where(x => x.Key.EndsWith(@"/") && x.Size == 0);
						result = new ListObjectsResponse();
						foreach (S3Object x in folders)
						{
							result.S3Objects.Add(x);
						}
						if (response.IsTruncated)
						{
							listRequest.Marker = response.NextMarker;
						}
						else
						{
							listRequest = null;
						}
					} while (listRequest != null);


				}
			}catch (Exception x)
			{
				MessageBox.Show(x.Message, "Erorr 1");
				result = null;
			}

			return result;
		}
		public S3DirectoryInfo ListFiles(string folder)
		{
			var client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2);
			var dir = new S3DirectoryInfo(client, bucketName, folder);


			ListObjectsRequest listRequest = new ListObjectsRequest
			{
				BucketName = bucketName,
				Prefix = folder
			};


			return dir;
		}
	}  
    
</s3object>

本地和远程文件和文件夹都列在 listView 和 treeView 对象中。该项目的 app.config 文件是我们需要放置凭证以访问 S3 对象的位置,以便 AWS SDK 可以访问它们:

<appsettings> <add key="AWSProfileName" value="Username"> <add key="AWSAccessKey" value="Access Key"> <add key="AWSSecretKey" value="Secret Key">

启动应用程序后,准备文件:

public PiBucket()
{
    InitializeComponent();
    PopulateTreeView();
    PopulateS3Tree();
}

两个 ContextMenuStrip 控件提供快捷方式来执行我们的功能。

还可以添加 StatusBar 并放置 StatusLabels 以显示所选文件、当前本地路径、S3 对象地址和网络状态标签。

要从 S3 文件夹中删除对象,必须选中项目复选框,然后右键单击,选择删除选项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值