文档中心 > 下载文件
下载文件

最近更新时间:2021-10-29

以下代码用于下载文件。

using System;

using System.Threading;

using Amazon.S3;

using Amazon.S3.Model;

 

namespace DownloadObject

{

    class Program

    {

        static void Main()

        {  

            var Ak = "xxx";

            var Sk = "xxx";

            var endpoint = "http://s3.test.com";

            var bucketNanme = "xxx";

            var objectName = "xxx";

            AmazonS3Client serviceClient = new AmazonS3Client(Ak,Sk,

            new AmazonS3Config{ ServiceURL = endpoint });

 

            try

            {  

                GetObjectResponse response;

                GetObjectRequest getObject = new GetObjectRequest{

                    BucketName = bucketNanme,

                    Key = objectName

                };

 

                response = serviceClient.GetObjectAsync(getObject).GetAwaiter().GetResult();

                CancellationTokenSource source = new CancellationTokenSource();

                CancellationToken token = source.Token;

                response.WriteResponseStreamToFileAsync(objectName, true, token);

                Thread.Sleep(5000); // 等待5秒,用于上一行的异步写文件

            

            } catch (AmazonS3Exception e) {

                Console.WriteLine(e.Data);

                throw;

            } catch (Exception e) {

                Console.WriteLine(e);

                throw;

            }

        }

    }

}