在C#中通过AWS.NET从S3存储中检索二进制数据

Ber*_*nDK 5 c# sdk amazon-s3 amazon-web-services

我已经在AWS SDK for .NET中测试了大多数包含的示例,它们都运行良好.

我可以在存储桶中PUT对象,LIST对象和DELETE对象,但是......我想删除原始文件并想要同步本地丢失的文件吗?

我想创建一个GET对象(通过键/名称和存储桶).我可以找到该对象,但如何通过API从S3读取二进制数据?

我是否必须为此编写自己的SOAP包装器,或者是否有"此处"的样本?:O)

希望有一个样本.它不需要处理例外等.我只需要看到连接,转发和存储文件的主要部分回到我的ASP.net或C#项目.

任何人???

Big*_*714 15

这是一个例子:

string bucketName = "bucket";
string key = "some/key/name.bin";
string dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "name.bin");

using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKeyID, AWSSecretAccessKeyID))
{
    GetObjectRequest getObjectRequest = new GetObjectRequest().WithBucketName(bucketName).WithKey(key);

    using (S3Response getObjectResponse = client.GetObject(getObjectRequest))
    {
        if (!File.Exists(dest))
        {
            using (Stream s = getObjectResponse.ResponseStream)
            {
                using (FileStream fs = new FileStream(dest, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = new byte[32768];
                    int bytesRead = 0;
                    do
                    {
                        bytesRead = s.Read(data, 0, data.Length);
                        fs.Write(data, 0, bytesRead);
                    }
                    while (bytesRead > 0);
                    fs.Flush();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)