메뉴
Amazon Simple Storage Service
개발자 안내서 (API 버전 2006-03-01)

.NET용 AWS SDK를 사용한 여러 객체 삭제

.NET용 AWS SDK는 여러 객체를 삭제하기 위한 편리한 메서드인 DeleteObjects를 제공합니다. 삭제하려는 각 객체에 대해 객체의 키 이름과 버전을 지정합니다. 버전 관리를 사용하지 않는 버킷의 경우, 버전 ID에 null을 지정합니다. 예외가 발생하면 DeleteObjectsException 응답을 검토하여 삭제되지 않은 객체와 이유를 확인합니다.

예 버전 관리 미사용 버킷에서 여러 객체 삭제

다음 C# 예제는 multi-object delete API를 사용하여 버전 관리 미사용 버킷에서 객체를 삭제합니다. 이 예제에서는 샘플 객체를 버킷에 업로드한 다음 DeleteObjects 메서드를 사용하여 단일 요청으로 객체를 삭제합니다. 이 예제에서는 버전 ID가 null이므로 DeleteObjectsRequest에서 객체 키 이름만 지정합니다.

실제 예제를 작성하여 테스트하는 방법에 대한 자세한 내용은Amazon S3 .NET 코드 예시 실행 단원을 참조하십시오.

using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class DeleteMultipleObjectsNonVersionedBucketTest { private const string bucketName = "*** versioning-enabled bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); MultiObjectDeleteAsync().Wait(); } static async Task MultiObjectDeleteAsync() { // Create sample objects (for subsequent deletion). var keysAndVersions = await PutObjectsAsync(3); // a. multi-object delete by specifying the key names and version IDs. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keysAndVersions // This includes the object keys and null version IDs. }; // You can add specific object key to the delete request using the .AddKey. // multiObjectDeleteRequest.AddKey("TickerReference.csv", null); try { DeleteObjectsResponse response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionErrorStatus(e); } } private static void PrintDeletionErrorStatus(DeleteObjectsException e) { // var errorResponse = e.ErrorResponse; DeleteObjectsResponse errorResponse = e.Response; Console.WriteLine("x {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects successfully deleted = {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects failed to delete = {0}", errorResponse.DeleteErrors.Count); Console.WriteLine("Printing error data..."); foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Object Key: {0}\t{1}\t{2}", deleteError.Key, deleteError.Code, deleteError.Message); } } static async Task<List<KeyVersion>> PutObjectsAsync(int number) { List<KeyVersion> keys = new List<KeyVersion>(); for (int i = 0; i < number; i++) { string key = "ExampleObject-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; PutObjectResponse response = await s3Client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, // For non-versioned bucket operations, we only need object key. // VersionId = response.VersionId }; keys.Add(keyVersion); } return keys; } } }

예 버전 관리 사용 버킷의 여러 객체 삭제

다음 C# 코드 예제는 multi-object delete API를 사용하여 버전 관리를 사용하는 버킷에서 객체를 삭제합니다. 이 예제에서는 다음 작업을 수행합니다.

  1. 샘플 객체를 만들고 각 객체의 키 이름과 버전 ID를 지정하여 삭제합니다. 이 작업에서는 특정 객체 버전을 삭제합니다.

  2. 샘플 객체를 만들고 키 이름만 지정하여 삭제합니다. 이 예제에서는 버전 ID를 지정하지 않으므로 이 작업은 삭제 마커만 추가합니다. 특정 객체 버전은 삭제하지 않습니다. 삭제 후 이러한 객체는 Amazon S3 콘솔에 표시되지 않습니다.

  3. 삭제 마커의 객체 키와 버전 ID를 지정하여 삭제 마커를 삭제합니다. 이 작업에서 삭제 마커를 삭제하면 해당 객체가 콘솔에 다시 표시됩니다.

실제 예제를 작성하여 테스트하는 방법에 대한 자세한 내용은Amazon S3 .NET 코드 예시 실행 단원을 참조하십시오.

using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class DeleteMultipleObjVersionedBucketTest { private const string bucketName = "*** versioning-enabled bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); DeleteMultipleObjectsFromVersionedBucketAsync().Wait(); } private static async Task DeleteMultipleObjectsFromVersionedBucketAsync() { // Delete objects (specifying object version in the request). await DeleteObjectVersionsAsync(); // Delete objects (without specifying object version in the request). var deletedObjects = await DeleteObjectsAsync(); // Additional exercise - remove the delete markers S3 returned in the preceding response. // This results in the objects reappearing in the bucket (you can // verify the appearance/disappearance of objects in the console). await RemoveDeleteMarkersAsync(deletedObjects); } private static async Task<List<DeletedObject>> DeleteObjectsAsync() { // Upload the sample objects. var keysAndVersions2 = await PutObjectsAsync(3); // Delete objects using only keys. Amazon S3 creates a delete marker and // returns its version ID in the response. List<DeletedObject> deletedObjects = await NonVersionedDeleteAsync(keysAndVersions2); return deletedObjects; } private static async Task DeleteObjectVersionsAsync() { // Upload the sample objects. var keysAndVersions1 = await PutObjectsAsync(3); // Delete the specific object versions. await VersionedDeleteAsync(keysAndVersions1); } private static void PrintDeletionReport(DeleteObjectsException e) { var errorResponse = e.Response; Console.WriteLine("No. of objects successfully deleted = {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects failed to delete = {0}", errorResponse.DeleteErrors.Count); Console.WriteLine("Printing error data..."); foreach (var deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Object Key: {0}\t{1}\t{2}", deleteError.Key, deleteError.Code, deleteError.Message); } } static async Task VersionedDeleteAsync(List<KeyVersion> keys) { // a. Perform a multi-object delete by specifying the key names and version IDs. var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keys // This includes the object keys and specific version IDs. }; try { Console.WriteLine("Executing VersionedDelete..."); DeleteObjectsResponse response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); } } static async Task<List<DeletedObject>> NonVersionedDeleteAsync(List<KeyVersion> keys) { // Create a request that includes only the object key names. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(); multiObjectDeleteRequest.BucketName = bucketName; foreach (var key in keys) { multiObjectDeleteRequest.AddKey(key.Key); } // Execute DeleteObjects - Amazon S3 add delete marker for each object // deletion. The objects disappear from your bucket. // You can verify that using the Amazon S3 console. DeleteObjectsResponse response; try { Console.WriteLine("Executing NonVersionedDelete..."); response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); throw; // Some deletes failed. Investigate before continuing. } // This response contains the DeletedObjects list which we use to delete the delete markers. return response.DeletedObjects; } private static async Task RemoveDeleteMarkersAsync(List<DeletedObject> deletedObjects) { var keyVersionList = new List<KeyVersion>(); foreach (var deletedObject in deletedObjects) { KeyVersion keyVersion = new KeyVersion { Key = deletedObject.Key, VersionId = deletedObject.DeleteMarkerVersionId }; keyVersionList.Add(keyVersion); } // Create another request to delete the delete markers. var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keyVersionList }; // Now, delete the delete marker to bring your objects back to the bucket. try { Console.WriteLine("Removing the delete markers ....."); var deleteObjectResponse = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} delete markers", deleteObjectResponse.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); } } static async Task<List<KeyVersion>> PutObjectsAsync(int number) { var keys = new List<KeyVersion>(); for (var i = 0; i < number; i++) { string key = "ObjectToDelete-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; var response = await s3Client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, VersionId = response.VersionId }; keys.Add(keyVersion); } return keys; } } }