這是一段時間,我不碰AmazonS3服務,但是這是你應該做的:
- 路徑list all object keys你想
每個鍵,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
對象全部刪除鍵。
謝謝,這工作。這很奇怪,我可以從「文件夾」列出,但我不能刪除「文件夾」 – Sinaesthetic
@Sinaesthetic檢查該「文件夾」鍵的權限 – balexandre
代碼更新:添加了一種方法來刪除所有鍵在一個動作,所以你可以保存刪除每個鍵的API行程... – balexandre