Amazon S3 lAmazon SDK for .NET - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon S3 lAmazon SDK for .NET

以下代码示例显示如何通过Amazon SDK for .NET使用 Amazon S3。

操作展示如何调用具体的 Amazon S3 函数的代码节选,这些节选介绍如何调用具体函数。

方案展示如何通过调用多个 Amazon S3 函数来完成特定任务的代码示例。

每个示例都包含一个指向 GitHub,其中包含了有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例显示如何将 Amazon S3 对象从一个存储桶复制到另一个存储桶。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Copies an object in an Amazon S3 bucket to a folder within the /// same bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where the /// object to copy is located.</param> /// <param name="objectName">The object to be copied.</param> /// <param name="folderName">The folder to which the object will /// be copied.</param> /// <returns>A boolean value that indicates the success or failure of /// the copy operation.</returns> public static async Task<bool> CopyObjectInBucketAsync( IAmazonS3 client, string bucketName, string objectName, string folderName) { try { var request = new CopyObjectRequest { SourceBucket = bucketName, SourceKey = objectName, DestinationBucket = bucketName, DestinationKey = $"{folderName}\\{objectName}", }; var response = await client.CopyObjectAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error copying object: '{ex.Message}'"); return false; } }
  • 有关详细信息,请参阅。CopyObjectAmazon SDK for .NETAPI 参考.

以下代码示例显示如何创建 Amazon S3 存储桶。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Shows how to create a new Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket to create.</param> /// <returns>A boolean value representing the success or failure of /// the bucket creation process.</returns> public static async Task<bool> CreateBucketAsync(IAmazonS3 client, string bucketName) { try { var request = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true, }; var response = await client.PutBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error creating bucket: '{ex.Message}'"); return false; } }
  • 有关详细信息,请参阅。CreateBucketAmazon SDK for .NETAPI 参考.

以下代码示例显示如何删除空的 Amazon S3 存储桶。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Shows how to delete an Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param> /// <returns>A boolean value that represents the success or failure of /// the delete operation.</returns> public static async Task<bool> DeleteBucketAsync(IAmazonS3 client, string bucketName) { var request = new DeleteBucketRequest { BucketName = bucketName, }; var response = await client.DeleteBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • 有关详细信息,请参阅。DeleteBucketAmazon SDK for .NETAPI 参考.

以下代码示例显示如何删除 Amazon S3 存储桶中的多个对象。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

从 Amazon S3 存储桶中删除所有对象。

/// <summary> /// Delete all of the objects stored in an existing Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket from which the /// contents will be deleted.</param> /// <returns>A boolean value that represents the success or failure of /// deleting all of the objects in the bucket.</returns> public static async Task<bool> DeleteBucketContentsAsync(IAmazonS3 client, string bucketName) { // Iterate over the contents of the bucket and delete all objects. var request = new ListObjectsV2Request { BucketName = bucketName, }; try { var response = await client.ListObjectsV2Async(request); do { response.S3Objects .ForEach(async obj => await client.DeleteObjectAsync(bucketName, obj.Key)); // If the response is truncated, set the request ContinuationToken // from the NextContinuationToken property of the response. request.ContinuationToken = response.NextContinuationToken; } while (response.IsTruncated); return true; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error deleting objects: {ex.Message}"); return false; } }
  • 有关详细信息,请参阅。DeleteObjectsAmazon SDK for .NETAPI 参考.

以下代码示例显示如何从 Amazon S3 存储桶中的对象读取数据。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Shows how to download an object from an Amazon S3 bucket to the /// local computer. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket where the object is /// currently stored.</param> /// <param name="objectName">The name of the object to download.</param> /// <param name="filePath">The path, including filename, where the /// downloaded object will be stored.</param> /// <returns>A boolean value indicating the success or failure of the /// download process.</returns> public static async Task<bool> DownloadObjectFromBucketAsync( IAmazonS3 client, string bucketName, string objectName, string filePath) { // Create a GetObject request var request = new GetObjectRequest { BucketName = bucketName, Key = objectName, }; // Issue request and remember to dispose of the response using GetObjectResponse response = await client.GetObjectAsync(request); try { // Save object to local file await response.WriteResponseStreamToFileAsync($"{filePath}\\{objectName}", true, System.Threading.CancellationToken.None); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error saving {objectName}: {ex.Message}"); return false; } }
  • 有关详细信息,请参阅。GetObjectAmazon SDK for .NETAPI 参考.

以下代码示例显示如何列出 Amazon S3 存储桶中的对象。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Shows how to list the objects in an Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket for which to list /// the contents.</param> /// <returns>A boolean value indicating the success or failure of the /// copy operation.</returns> public static async Task<bool> ListBucketContentsAsync(IAmazonS3 client, string bucketName) { try { var request = new ListObjectsV2Request { BucketName = bucketName, MaxKeys = 5, }; Console.WriteLine("--------------------------------------"); Console.WriteLine($"Listing the contents of {bucketName}:"); Console.WriteLine("--------------------------------------"); var response = new ListObjectsV2Response(); do { response = await client.ListObjectsV2Async(request); response.S3Objects .ForEach(obj => Console.WriteLine($"{obj.Key,-35}{obj.LastModified.ToShortDateString(),10}{obj.Size,10}")); // If the response is truncated, set the request ContinuationToken // from the NextContinuationToken property of the response. request.ContinuationToken = response.NextContinuationToken; } while (response.IsTruncated); return true; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects."); return false; } }
  • 有关详细信息,请参阅。ListObjectsAmazon SDK for .NETAPI 参考.

以下代码示例显示如何将对象上传到 Amazon S3 存储桶。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

/// <summary> /// Shows how to upload a file from the local computer to an Amazon S3 /// bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The Amazon S3 bucket to which the object /// will be uploaded.</param> /// <param name="objectName">The object to upload.</param> /// <param name="filePath">The path, including file name, of the object /// on the local computer to upload.</param> /// <returns>A boolean value indicating the success or failure of the /// upload procedure.</returns> public static async Task<bool> UploadFileAsync( IAmazonS3 client, string bucketName, string objectName, string filePath) { var request = new PutObjectRequest { BucketName = bucketName, Key = objectName, FilePath = filePath, }; var response = await client.PutObjectAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully uploaded {objectName} to {bucketName}."); return true; } else { Console.WriteLine($"Could not upload {objectName} to {bucketName}."); return false; } }
  • 有关详细信息,请参阅。PutObjectAmazon SDK for .NETAPI 参考.

场景

以下代码示例显示了如何:

  • 创建存储桶。

  • 将文件上传到存储桶。

  • 从存储桶下载对象。

  • 将对象复制到存储桶中的子文件夹。

  • 列出存储桶中的对象。

  • 删除存储桶中的对象。

  • 删除存储桶。

Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅GitHub.

using System; using System.IO; using System.Threading.Tasks; using Amazon.S3; public class S3_Basics { public static async Task Main() { // Create an Amazon S3 client object. The constructor uses the // default user installed on the system. To work with Amazon S3 // features in a different AWS Region, pass the AWS Region as a // parameter to the client constructor. IAmazonS3 client = new AmazonS3Client(); string bucketName = string.Empty; string filePath = string.Empty; string keyName = string.Empty; Console.WriteLine("Amazon Simple Storage Service (Amazon S3) basic"); Console.WriteLine("procedures. This application will:"); Console.WriteLine("\n\t1. Create a bucket"); Console.WriteLine("\n\t2. Upload an object to the new bucket"); Console.WriteLine("\n\t3. Copy the uploaded object to a folder in the bucket"); Console.WriteLine("\n\t4. List the items in the new bucket"); Console.WriteLine("\n\t5. Delete all the items in the bucket"); Console.WriteLine("\n\t6. Delete the bucket"); Console.WriteLine("----------------------------------------------------------"); // Create a bucket. Console.WriteLine("\nCreate a new Amazon S3 bucket.\n"); Console.Write("Please enter a name for the new bucket: "); bucketName = Console.ReadLine(); var success = await S3Bucket.CreateBucketAsync(client, bucketName); if (success) { Console.WriteLine($"Successfully created bucket: {bucketName}.\n"); } else { Console.WriteLine($"Could not create bucket: {bucketName}.\n"); } Console.WriteLine("Upload a file to the new bucket."); // Get the local path and filename for the file to upload. while (string.IsNullOrEmpty(filePath)) { Console.Write("Please enter the path and filename of the file to upload: "); filePath = Console.ReadLine(); // Confirm that the file exists on the local computer. if (!File.Exists(filePath)) { Console.WriteLine($"Couldn't find {filePath}. Try again.\n"); filePath = string.Empty; } } // Get the file name from the full path. keyName = Path.GetFileName(filePath); success = await S3Bucket.UploadFileAsync(client, bucketName, keyName, filePath); if (success) { Console.WriteLine($"Successfully uploaded {keyName} from {filePath} to {bucketName}.\n"); } else { Console.WriteLine($"Could not upload {keyName}.\n"); } // Set the file path to an empty string to avoid overwriting the // file we just uploaded to the bucket. filePath = string.Empty; // Now get a new location where we can save the file. while (string.IsNullOrEmpty(filePath)) { // First get the path to which the file will be downloaded. Console.Write("Please enter the path where the file will be downloaded: "); filePath = Console.ReadLine(); // Confirm that the file exists on the local computer. if (File.Exists($"{filePath}\\{keyName}")) { Console.WriteLine($"Sorry, the file already exists in that location.\n"); filePath = string.Empty; } } // Download an object from a bucket. success = await S3Bucket.DownloadObjectFromBucketAsync(client, bucketName, keyName, filePath); if (success) { Console.WriteLine($"Successfully downloaded {keyName}.\n"); } else { Console.WriteLine($"Sorry, could not download {keyName}.\n"); } // Copy the object to a different folder in the bucket. string folderName = string.Empty; while (string.IsNullOrEmpty(folderName)) { Console.Write("Please enter the name of the folder to copy your object to: "); folderName = Console.ReadLine(); } while (string.IsNullOrEmpty(keyName)) { // Get the name to give to the object once uploaded. Console.Write("Enter the name of the object to copy: "); keyName = Console.ReadLine(); } await S3Bucket.CopyObjectInBucketAsync(client, bucketName, keyName, folderName); // List the objects in the bucket. await S3Bucket.ListBucketContentsAsync(client, bucketName); // Delete the contents of the bucket. await S3Bucket.DeleteBucketContentsAsync(client, bucketName); // Deleting the bucket too quickly after deleting its contents will // cause an error that the bucket isn't empty. So... Console.WriteLine("Press <Enter> when you are ready to delete the bucket."); _ = Console.ReadLine(); // Delete the bucket. await S3Bucket.DeleteBucketAsync(client, bucketName); } }