文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
CopyObject
搭配 AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 CopyObject
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- AWS SDK for .NET
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 using System; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; public class CopyObject { public static async Task Main() { // Specify the AWS Region where your buckets are located if it is // different from the AWS Region of the default user. IAmazonS3 s3Client = new AmazonS3Client(); // Remember to change these values to refer to your Amazon S3 objects. string sourceBucketName = "amzn-s3-demo-bucket1"; string destinationBucketName = "amzn-s3-demo-bucket2"; string sourceObjectKey = "testfile.txt"; string destinationObjectKey = "testfilecopy.txt"; Console.WriteLine($"Copying {sourceObjectKey} from {sourceBucketName} to "); Console.WriteLine($"{destinationBucketName} as {destinationObjectKey}"); var response = await CopyingObjectAsync( s3Client, sourceObjectKey, destinationObjectKey, sourceBucketName, destinationBucketName); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("\nCopy complete."); } } /// <summary> /// This method calls the AWS SDK for .NET to copy an /// object from one Amazon S3 bucket to another. /// </summary> /// <param name="client">The Amazon S3 client object.</param> /// <param name="sourceKey">The name of the object to be copied.</param> /// <param name="destinationKey">The name under which to save the copy.</param> /// <param name="sourceBucketName">The name of the Amazon S3 bucket /// where the file is located now.</param> /// <param name="destinationBucketName">The name of the Amazon S3 /// bucket where the copy should be saved.</param> /// <returns>Returns a CopyObjectResponse object with the results from /// the async call.</returns> public static async Task<CopyObjectResponse> CopyingObjectAsync( IAmazonS3 client, string sourceKey, string destinationKey, string sourceBucketName, string destinationBucketName) { var response = new CopyObjectResponse(); try { var request = new CopyObjectRequest { SourceBucket = sourceBucketName, SourceKey = sourceKey, DestinationBucket = destinationBucketName, DestinationKey = destinationKey, }; response = await client.CopyObjectAsync(request); } catch (AmazonS3Exception ex) { Console.WriteLine($"Error copying object: '{ex.Message}'"); } return response; } }
使用條件式請求複製物件。
/// <summary> /// Copies an object from one Amazon S3 bucket to another with a conditional request. /// </summary> /// <param name="sourceKey">The key of the source object to copy.</param> /// <param name="destKey">The key of the destination object.</param> /// <param name="sourceBucket">The source bucket of the object.</param> /// <param name="destBucket">The destination bucket of the object.</param> /// <param name="conditionType">The type of condition to apply, e.g. 'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'.</param> /// <param name="conditionDateValue">The value to use for the condition for dates.</param> /// <param name="etagConditionalValue">The value to use for the condition for etags.</param> /// <returns>True if the conditional copy is successful, False otherwise.</returns> public async Task<bool> CopyObjectConditional(string sourceKey, string destKey, string sourceBucket, string destBucket, S3ConditionType conditionType, DateTime? conditionDateValue = null, string? etagConditionalValue = null) { try { var copyObjectRequest = new CopyObjectRequest { DestinationBucket = destBucket, DestinationKey = destKey, SourceBucket = sourceBucket, SourceKey = sourceKey }; switch (conditionType) { case S3ConditionType.IfMatch: copyObjectRequest.ETagToMatch = etagConditionalValue; break; case S3ConditionType.IfNoneMatch: copyObjectRequest.ETagToNotMatch = etagConditionalValue; break; case S3ConditionType.IfModifiedSince: copyObjectRequest.ModifiedSinceDateUtc = conditionDateValue.GetValueOrDefault(); break; case S3ConditionType.IfUnmodifiedSince: copyObjectRequest.UnmodifiedSinceDateUtc = conditionDateValue.GetValueOrDefault(); break; default: throw new ArgumentOutOfRangeException(nameof(conditionType), conditionType, null); } await _amazonS3.CopyObjectAsync(copyObjectRequest); _logger.LogInformation($"Conditional copy successful for key {destKey} in bucket {destBucket}."); return true; } catch (AmazonS3Exception e) { if (e.ErrorCode == "PreconditionFailed") { _logger.LogError("Conditional copy failed: Precondition failed"); } else if (e.ErrorCode == "304") { _logger.LogError("Conditional copy failed: Object not modified"); } else { _logger.LogError($"Unexpected error: {e.ErrorCode}"); throw; } return false; } }
-
如需 API 詳細資訊,請參閱《AWS SDK for .NET API 參考》中的 CopyObject。
-