首页 > 解决方案 > 使用 C# 从 s3 存储桶下载文件

问题描述

我对 AWS s3 存储桶概念有点陌生。我想从 s3 存储桶中的文件夹“TODAY FILE1”下载文件并使用它。我知道如何使用命令提示符在命令行中执行此操作。我不知道如何在 C# 中实现。

认为

这是我做的命令提示符

C:\> aws s3 cp "s3://mys3bucket-output/TODAY FILE1" . --recursive

这就是我所做的 C# 程序并得到错误

string accessKey = "abc123";
string secretKey = "secret123";
string bucketName = "mys3bucket-output"
TransferUtility fileTransferUtility =   new TransferUtility(new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast2));


BasicAWSCredentials basicCredentials = new BasicAWSCredentials(accessKey,secretKey);
AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey), Amazon.RegionEndpoint.USEast2);
ListObjectsRequest request = new ListObjectsRequest();

ListObjectsResponse response = s3Client.ListObjects(request.BucketName= bucketName, request.Prefix="TODAY FILE1/");

foreach (S3Object obj in response.S3Objects)
{
    try
    {
        Console.WriteLine("{0}", obj.Key);
        fileTransferUtility.Download(@"C:\Temp", bucketName, obj.Key);

    }
    catch (Exception Excep)
    {
        Console.WriteLine(Excep.Message, Excep.InnerException);
    }
}

我收到异常 Amazon.Runtime.AmazonServiceException: 'Access to the path 'C:\Temp' is denied

不知道怎么办 谢谢MR

标签: c#amazon-s3

解决方案


在写入之前创建文件:

foreach (S3Object obj in response.S3Objects)
{
    try
    {
        string filename = directoryPath + "\\" + obj.Key;
        FileStream fs = File.Create(filename);
        fs.Close();
        Console.WriteLine("{0}", obj.Key);
        fileTransferUtility.Download(filename, bucketName, obj.Key);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message, ex.InnerException);
    }
}

推荐阅读