使用API​​从Amazon S3删除文件夹

时间:2015-10-08 13:54:46

标签: c# amazon-web-services amazon-s3

我正在尝试删除文件夹中基本上是日期的所有文件。

假如文件夹" 08-10-2015 "下有 100个文件,而不是发送所有这100个文件名,我想要发送文件夹名称。

我正在尝试下面的代码,它对我不起作用。

        DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest();

        multiObjectDeleteRequest.BucketName = bucketName;

        multiObjectDeleteRequest.AddKey(keyName + "/" + folderName + "/");


        AmazonS3Config S3Config = new AmazonS3Config()
        {
            ServiceURL = string.Format(servicehost)
        };

        using (IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(accesskey, secretkey, S3Config))
        {
            try
            {
                DeleteObjectsResponse response = client.DeleteObjects(multiObjectDeleteRequest);
                Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count);

            }
            catch (DeleteObjectsException e)
            {
                // Process exception.
            }

我正在使用上面的代码,但它无效。

2 个答案:

答案 0 :(得分:11)

我认为您可以使用以下代码删除整个文件夹:

 AmazonS3Config cfg = new AmazonS3Config();
 cfg.RegionEndpoint = Amazon.RegionEndpoint.EUCentral1;
 string bucketName = "your bucket name";
 AmazonS3Client s3Client = new AmazonS3Client("your access key", "your secret key", cfg);
 S3DirectoryInfo directoryToDelete = new S3DirectoryInfo(s3Client, bucketName, "your folder name or full folder key");
 directoryToDelete.Delete(true); // true will delete recursively in folder inside

我正在使用amazon AWSSDK.Core和AWSSDK.S3版本3.1.0.0 for .net 3.5。 我希望它可以帮到你

答案 1 :(得分:3)

你必须:

  1. 列出文件夹
  2. 中的所有对象
  3. 检索每个对象的密钥
  4. 将此密钥添加到多个删除对象请求
  5. 发出删除所有对象的请求

     AmazonS3Config S3Config = new AmazonS3Config()
        {
            ServiceURL = "s3.amazonaws.com",
            CommunicationProtocol = Amazon.S3.Model.Protocol.HTTP,
        };
    
     const string AWS_ACCESS_KEY = "xxxxxxxxxxxxxxxx";
     const string AWS_SECRET_KEY = "yyyyyyyyyyyyyyyy";            
     AmazonS3Client client = new AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, S3Config);
    
        DeleteObjectsRequest request2 = new DeleteObjectsRequest();
        ListObjectsRequest request = new ListObjectsRequest
        {
            BucketName = "yourbucketname",
            Prefix = "yourprefix"
    
        };
    
        ListObjectsResponse response = await client.ListObjectsAsync(request);
                // Process response.
                foreach (S3Object entry in response.S3Objects)
                {
    
                    request2.AddKey(entry.Key);
                }
        request2.BucketName = "yourbucketname";
        DeleteObjectsResponse response2 = await client.DeleteObjectsAsync(request2);