使用高階 .NET TransferUtility 類別上傳目錄 - Amazon Simple Storage Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用高階 .NET TransferUtility 類別上傳目錄

您可以使用 TransferUtility 類別,上傳整個目錄。根據預設,API 只會上傳指定目錄根目錄的檔案。但您可以指定以遞迴方式,上傳所有子目錄中的檔案。

也可以根據一些篩選條件,指定篩選運算式,來選取指定目錄中的檔案。例如,若只要從目錄上傳 .pdf 檔案,可以指定 "*.pdf" 的篩選運算式。

從目錄上傳檔案時,無法指定結果物件的金鑰名稱。Amazon S3 使用原始檔案路徑,建構金鑰名稱。例如,假設您有一個目錄為 c:\myfolder,其結構如下:

C:\myfolder \a.txt \b.pdf \media\ An.mp3

當您上傳此目錄時,Amazon S3 會使用下列金鑰名稱:

a.txt b.pdf media/An.mp3

下列 C# 範例會將目錄上傳至 Amazon S3 儲存貯體。此顯示如何使用不同的 TransferUtility.UploadDirectory 多載上傳目錄。每個後續的呼叫都會上傳取代前一個上傳。如需有關設定和執行程式碼範例的資訊,請參閱 AWS SDK for .NET 中的 Word for .Word 入門 AWS SDK NET 開發人員指南

using Amazon; using Amazon.S3; using Amazon.S3.Transfer; using System; using System.IO; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class UploadDirMPUHighLevelAPITest { private const string existingBucketName = "*** bucket name ***"; private const string directoryPath = @"*** directory path ***"; // The example uploads only .txt files. private const string wildCard = "*.txt"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; static void Main() { s3Client = new AmazonS3Client(bucketRegion); UploadDirAsync().Wait(); } private static async Task UploadDirAsync() { try { var directoryTransferUtility = new TransferUtility(s3Client); // 1. Upload a directory. await directoryTransferUtility.UploadDirectoryAsync(directoryPath, existingBucketName); Console.WriteLine("Upload statement 1 completed"); // 2. Upload only the .txt files from a directory // and search recursively. await directoryTransferUtility.UploadDirectoryAsync( directoryPath, existingBucketName, wildCard, SearchOption.AllDirectories); Console.WriteLine("Upload statement 2 completed"); // 3. The same as Step 2 and some optional configuration. // Search recursively for .txt files to upload. var request = new TransferUtilityUploadDirectoryRequest { BucketName = existingBucketName, Directory = directoryPath, SearchOption = SearchOption.AllDirectories, SearchPattern = wildCard }; await directoryTransferUtility.UploadDirectoryAsync(request); Console.WriteLine("Upload statement 3 completed"); } catch (AmazonS3Exception e) { Console.WriteLine( "Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine( "Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } } }