简体   繁体   中英

Download and save file from Amazon S3 with Unity C#

I am following Amazon's tutorial on S3 but I cannot download file and save it to Streaming Resources. Instead I am downloading file content.

ResultText.text = string.Format("fetching {0} from bucket {1}", SampleFileName, S3BucketName);
Client.GetObjectAsync(S3BucketName, SampleFileName, (responseObj) =>
{
    string data = null;
    var response = responseObj.Response;
    if (response.ResponseStream != null)
    {
        using (StreamReader reader = new StreamReader(response.ResponseStream))
        {
            data = reader.ReadToEnd();
        }

        ResultText.text += "\n";
        ResultText.text += data;
    }
});

I understand that I should convert the response.ResponseStream into File but I tried many different solutions and I could not make it working.

I understand that I should convert the response.ResponseStream into File but ....

You do not convert it into a file you read from it and write the content to a file. There are plenty of built in methods that help with this but the steps are simple. Open/Create a file stream and then write from the response stream to the file stream.

if (response.ResponseStream != null)
{
    using (var fs = System.IO.File.Create(@"c:\some-folder\file-name.ext"))
    {
        byte[] buffer = new byte[81920];
        int count;
        while ((count = response.ResponseStream.Read(buffer, 0, buffer.Length)) != 0)
            fs.Write(buffer, 0, count);
        fs.Flush();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM