Retrieve binary data from S3 storage through AWS.NET in C#

浪子不回头ぞ 提交于 2019-12-09 18:25:48

问题


I've tested most of the included samples in the AWS SDK for .NET and they all works fine.

I can PUT objects, LIST objects and DELETE objects in a bucket, but... lets say I delete the original and want to sync those files missing locally?

I would like to make a GET object (by key/name and bucket ofcause). I can find the object, but how do I read the binary data from S3 through the API?

Do I have to write my own SOAP wrapper for this or is there some kinda sample for this out "here" ? :o)

In hope of a sample. It does not have to tollerate execeptions etc. I just need to see the main parts that connects, retreives and stores the file back on my ASP.net or C# project.

Anyone???


回答1:


Here is an example:

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();
                }
            }
        }
    }
}


来源:https://stackoverflow.com/questions/2455454/retrieve-binary-data-from-s3-storage-through-aws-net-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!