2015-10-08 85 views
2

我想刪除基本上是日期的文件夾內的所有文件。使用API​​從Amazon S3刪除文件夾

假設,如果有100文件文件夾下的「2015年8月10日」,而不是將所有的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. 
      } 

我正在使用上面的代碼,它不工作。

+4

S3 API不允許你直接刪除文件夾,因爲文件夾在S3中不存在(它們是對用戶的邏輯表示)。相反,您必須將[多個對象鍵指定爲'DeleteObjectsRequest'](http://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html)。您可以通過指定['ListObjectsRequest'](http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_S3_Model_ListObjectsRequest.htm)的'Prefix'屬性來搜索'文件夾'下的所有密鑰,所以你可以把它和刪除結合起來做你想做的事情。 – birryree

回答

0

你必須:

  1. 列表中的文件夾中的所有對象
  2. 的檢索關鍵字爲每個對象
  3. 該鍵添加到多個刪除對象請求
  4. 使請求刪除所有物體

    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 = client.ListObjects(request); 
          // Process response. 
          foreach (S3Object entry in response.S3Objects) 
          { 
    
           request2.AddKey(entry.Key); 
          } 
        request2.BucketName = "yourbucketname"; 
        DeleteObjectsResponse response2 = client.DeleteObjects(request2); 
    
8

我想你可以用下面的代碼刪除整個文件夾:

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 

我使用亞馬遜AWSSDK.Core和AWSSDK.S3版本3.1.0.0爲.NET 3.5。 我希望它可以幫助你

+0

工程就像一個魅力!謝謝! – forrert