目录
介绍
使用代码
设置
兴趣点
- 下载 PiBox.zip - 18.8 MB
在本文中,我将向您展示如何在Amazon Web Services中创建一个S3存储桶,然后从您的C#代码访问和管理其对象。
使用代码在使用此代码之前,您需要拥有一个AWS账户并知道如何在AWS中创建S3存储桶。我提供了一个分步指南,解释了如何创建S3存储桶、使用 AWS中的IAM添加用户以及设置组策略来规范对S3资源的访问。
您可以在此处查看我的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 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;
}
}
本地和远程文件和文件夹都列在listView和treeView对象中。所以,你可以浏览。该项目的app.config文件是我们需要放置凭证以访问S3对象的位置,以便AWS SDK可以访问它们:
除此之外,我还定义了另一个属性来存储存储桶名称。
启动应用程序后,我们准备文件:
public PiBucket()
{
InitializeComponent();
PopulateTreeView();
PopulateS3Tree();
}
两个ContextMenuStrip控件提供快捷方式来执行我们的功能。
我还添加了StatusBar并放置了StatusLabels以显示所选文件、当前本地路径、S3对象地址和网络状态标签。
要从S3文件夹中删除对象,您必须选中项目复选框,然后右键单击,选择删除选项。
设置我希望这个项目尽可能地可定制,所以我决定添加设置屏幕,以便我可以在不同的AWS账户和S3对象之间切换:
如您所见,设置表单提供了两种方法来存储和恢复app.config文件中的应用程序设置值。
private void ShowValues()
{
try
{
textProfile.Text = ConfigurationManager.AppSettings.Get("AWSProfileName");
textAccess.Text = ConfigurationManager.AppSettings.Get("AWSAccessKey");
textSecret.Text = ConfigurationManager.AppSettings.Get("AWSSecretKey");
textBucket.Text = Properties.Settings.Default.bucket;
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Error 23", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
此方法将更改保存到app.config:
private void StoreValues()
{
try
{
if (!string.IsNullOrEmpty(textAccess.Text) && !string.IsNullOrEmpty(textBucket.Text) && !string.IsNullOrEmpty(textSecret.Text) && !string.IsNullOrEmpty(textProfile.Text))
{
Setconfig.UpdateAppSettings("AWSProfileName", textProfile.Text);
Setconfig.UpdateAppSettings("AWSAccessKey", textAccess.Text);
Setconfig.UpdateAppSettings("AWSSecretKey", textSecret.Text);
Properties.Settings.Default.bucket = textBucket.Text;
Properties.Settings.Default.Save();
MessageBox.Show("Restart the software for the changes to take effect.", "Setting", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}catch(Exception x)
{
MessageBox.Show(x.Message, "Error 33", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
一旦弄清楚一切是如何工作的,您将改进此代码并构建自己的代码。我在几个小时内编写了这段代码,我确信它还有很大的改进空间。
https://www.codeproject.com/Tips/5315576/Manage-AWS-S3-Objects-in-Csharp