简体   繁体   中英

Can I monitor the progress of an S3 download using the AWS SDK?

I'm using the AWS SDK package from Nuget to download files from S3. This involves creating a GetObject request. Amazon has an example of how to do this in their documentation, although I'm actually using the async version of the method.

My code to download a file looks something like this:

using (var client = new AmazonS3Client(accessKey, secretAccessKey, RegionEndpoint.USEast1))
{
    var request = new GetObjectRequest
    {
        BucketName = "my-bucket",
        Key = "file.exe"
    };

    using (var response = await client.GetObjectAsync(request))
    {
        response.WriteResponseStreamToFile(@"C:\Downloads\file.exe");
    }
}

This works; it downloads the file successfully. However, it seems like a little bit of a black box, in that I never really know how long it's going to take to download the file. What I'm hoping to do is get some sort of Progress event so that I can display a nice WPF ProgressBar and watch the download progress. This means I would need to know the size of the file and the number of bytes downloaded, and I'm not sure if there's a way to do that with the AWS SDK.

You can do:

using (var response = client.GetObject(request))
{
  response.WriteObjectProgressEvent += Response_WriteObjectProgressEvent;
  response.WriteResponseStreamToFile(@"C:\Downloads\file.exe");
}

private static void Response_WriteObjectProgressEvent(object sender, WriteObjectProgressArgs e)
{
  Debug.WriteLine($"Tansfered: {e.TransferredBytes}/{e.TotalBytes} - Progress: {e.PercentDone}%");
}

Can you hook in to the WriteObjectProgressEvent object? If you subscribe to events from this object your function will be called multiple times during the download. It will receive the number of bytes that are downloaded/remaining so you can build a progress indicator.

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