2015-12-23 40 views
1

假設在我的桶中存在以下文件上S3如何刪除我的存儲桶中所有對象的「子女」?

mybucket/folder1/folder2/myfile.txt 
mybucket/folder1/folder2/myfile2.txt 
mybucket/folder1/folder4/myfile3.txt 

我想要做的就是刪除mybucket/folder1/folder2/下生活在沒有實際知道文件存在正是所有文件。我知道文件夾不是真實的,實際上是對象鍵,但我仍然需要達到這種效果。

我試過刪除mybucket/folder1/folder2/(有和沒有結尾的斜線),但似乎沒有發生任何事情;沒有東西被刪除。有沒有錯誤和HttpResponse對象是204

回答

3

這是一段時間,我不碰AmazonS3服務,但是這是你應該做的:

  1. 路徑list all object keys你想
  2. 每個鍵,issue a delete action獲得所有按鍵和delete them in one go

代碼應該是這樣(的例子粗略編輯建議):

static IAmazonS3 client; 


static void DeleteFolderContents(string bucketName, string folderPath) 
{ 
    using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1)) 
    { 
     var allKeys = GetFolderContents(bucketName, fodlerPath);  
     var allDeletes = DeleteAllKeys(bucketName, allKeys); 

     // allDeletes has # of deleted objects 
    } 
} 

// using DeleteObjectsRequest (all keys at once) 
static int DeleteAllKeys(string bucketName, List<string> allKeys) 
{ 
    var multiObjectDeleteRequest = new DeleteObjectsRequest(); 
    multiObjectDeleteRequest.BucketName = bucketName; 

    foreach(var key in allKeys) 
     multiObjectDeleteRequest.AddKey(key, null); // version ID is null 

    try 
    { 
     var response = client.DeleteObjects(multiObjectDeleteRequest); 
     return response.DeletedObjects.Count; 
    } 
    catch (DeleteObjectsException e) 
    { 
     // throw exception. 
    } 

    return 0; 
} 

// delete one by one 
static void DeleteKey(string bucketName, string keyName) 
{ 
    DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest 
    { 
     BucketName = bucketName, 
     Key = keyName 
    }; 
    try 
    { 
     client.DeleteObject(deleteObjectRequest); 
    } 
    catch (AmazonS3Exception s3Exception) 
    { 
     // throw 
    } 
} 

// list all keys for a given path 
static List<string> 
    GetFolderContents(string bucketName, string folderPath) 
{ 
    var r = new List<string>(); 

    try 
    { 
     ListObjectsRequest request = new ListObjectsRequest 
     { 
      BucketName = bucketName, 
      Prefix = folderPath, 
      MaxKeys = 100 
     }; 

     do 
     { 
      ListObjectsResponse response = client.ListObjects(request); 

      foreach (S3Object entry in response.S3Objects) 
       r.Add(entry.Key); 

      // If response is truncated, set the marker to get the next 
      // set of keys. 
      if (response.IsTruncated) 
       request.Marker = response.NextMarker; 
      else 
       request = null; 
     } while (request != null); 
    } 
    catch (AmazonS3Exception amazonS3Exception) 
    { 
     // throw error 
    } 
} 

您還可以通過looking at this article找到一種方法來收聽文件夾中的所有密鑰。


編輯:加了一個行動呼籲使用DeleteObjectsRequest對象全部刪除鍵。

+0

謝謝,這工作。這很奇怪,我可以從「文件夾」列出,但我不能刪除「文件夾」 – Sinaesthetic

+0

@Sinaesthetic檢查該「文件夾」鍵的權限 – balexandre

+0

代碼更新:添加了一種方法來刪除所有鍵在一個動作,所以你可以保存刪除每個鍵的API行程... – balexandre

相關問題