

第 4 版 (V4) 適用於 .NET 的 AWS SDK 已發行！

如需有關中斷變更和遷移應用程式的資訊，請參閱[遷移主題](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

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

# 使用 的簡單跨平台應用程式 適用於 .NET 的 AWS SDK
<a name="quick-start-s3-1-cross"></a>

本教學課程使用 適用於 .NET 的 AWS SDK 和 .NET Core 進行跨平台開發。本教學課程說明如何使用 SDK 列出您擁有的 [Amazon S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)體，並選擇性地建立儲存貯體。

您將使用 .NET 命令列界面 (CLI) 等跨平台工具來執行此教學課程。如需設定開發環境的其他方式，請參閱 [安裝和設定 的工具鏈 適用於 .NET 的 AWS SDK](net-dg-dev-env.md)。

**在 Windows、Linux 或 macOS 上進行跨平台 .NET 開發時需要：**
+ Microsoft [.NET Core 軟體開發套件](https://learn.microsoft.com/en-us/dotnet/fundamentals/) 2.1 版、3.1 版或更新版本，包括 .NET 命令列界面 (CLI) (**`dotnet`**) 以及 .NET Core 執行時間。
+ 程式碼編輯器或整合式開發環境 (IDE)，適用於您的作業系統和需求。這通常是為 .NET Core 提供一些支援。

  舉例來說，包括 [Microsoft Visual Studio 程式碼 (VS 程式碼)](https://code.visualstudio.com/)、[JetBrains Rider](https://www.jetbrains.com/rider/) 和 [Microsoft Visual Studio](https://visualstudio.microsoft.com/vs/)。

**注意**  
使用這些教學課程之前，您必須先[安裝工具鏈](net-dg-dev-env.md)並[設定 SDK 身分驗證](creds-idc.md)。

## 步驟
<a name="s3-1-cross-steps"></a>
+ [建立專案](#s3-1-cross-create-project)
+ [建立程式碼](#s3-1-cross-code)
+ [執行應用程式](#s3-1-cross-run)
+ [清除](#s3-1-cross-clean-up)

## 建立專案
<a name="s3-1-cross-create-project"></a>

1. 開啟命令提示字元或終端機。尋找或建立可在其下建立 .NET 專案的作業系統資料夾。

1. 在該資料夾中，執行下列命令以建立 .NET 專案。

   ```
   dotnet new console --name S3CreateAndList
   ```

1. 移至新建立的`S3CreateAndList`資料夾並執行下列命令：

   ```
   dotnet add package AWSSDK.S3
   dotnet add package AWSSDK.SecurityToken
   dotnet add package AWSSDK.SSO
   dotnet add package AWSSDK.SSOOIDC
   ```

   上述命令會從 NuGet 套件[管理員安裝 NuGet 套件](https://www.nuget.org/profiles/awsdotnet)。由於我們確切知道本教學課程所需的 NuGet 套件，因此現在可以執行此步驟。在開發期間，所需的套件也很常見。發生這種情況時，即可執行類似的命令。

## 建立程式碼
<a name="s3-1-cross-code"></a>

1. 在 `S3CreateAndList` 資料夾中，在程式碼編輯器中尋找並開啟 `Program.cs`。

1. 以下列程式碼取代內容，並儲存檔案。

   ```
   using System;
   using System.Threading.Tasks;
   
   // NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC
   using Amazon.Runtime;
   using Amazon.Runtime.CredentialManagement;
   using Amazon.S3;
   using Amazon.S3.Model;
   using Amazon.SecurityToken;
   using Amazon.SecurityToken.Model;
   
   namespace S3CreateAndList
   {
       class Program
       {
           // This code is part of the quick tour in the developer guide.
           // See https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/quick-start.html
           // for complete steps.
           // Requirements:
           // - An SSO profile in the SSO user's shared config file with sufficient privileges for
   		//   STS and S3 buckets.
           // - An active SSO Token.
           //    If an active SSO token isn't available, the SSO user should do the following:
           //    In a terminal, the SSO user must call "aws sso login".
   
           // Class members.
           static async Task Main(string[] args)
           {
               // Get SSO credentials from the information in the shared config file.
               // For this tutorial, the information is in the [default] profile.
               var ssoCreds = LoadSsoCredentials("default");
   
               // Display the caller's identity.
               var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds);
               Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");
   
               // Create the S3 client is by using the SSO credentials obtained earlier.
               var s3Client = new AmazonS3Client(ssoCreds);
   
               // Parse the command line arguments for the bucket name.
               if (GetBucketName(args, out String bucketName))
               {
                   // If a bucket name was supplied, create the bucket.
                   // Call the API method directly
                   try
                   {
                       Console.WriteLine($"\nCreating bucket {bucketName}...");
                       var createResponse = await s3Client.PutBucketAsync(bucketName);
                       Console.WriteLine($"Result: {createResponse.HttpStatusCode.ToString()}");
                   }
                   catch (Exception e)
                   {
                       Console.WriteLine("Caught exception when creating a bucket:");
                       Console.WriteLine(e.Message);
                   }
               }
   
               // Display a list of the account's S3 buckets.
               Console.WriteLine("\nGetting a list of your buckets...");
               var listResponse = await s3Client.ListBucketsAsync();
               Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}");
               foreach (S3Bucket b in listResponse.Buckets)
               {
                   Console.WriteLine(b.BucketName);
               }
               Console.WriteLine();
           }
   
           // 
           // Method to parse the command line.
           private static Boolean GetBucketName(string[] args, out String bucketName)
           {
               Boolean retval = false;
               bucketName = String.Empty;
               if (args.Length == 0)
               {
                   Console.WriteLine("\nNo arguments specified. Will simply list your Amazon S3 buckets." +
                     "\nIf you wish to create a bucket, supply a valid, globally unique bucket name.");
                   bucketName = String.Empty;
                   retval = false;
               }
               else if (args.Length == 1)
               {
                   bucketName = args[0];
                   retval = true;
               }
               else
               {
                   Console.WriteLine("\nToo many arguments specified." +
                     "\n\ndotnet_tutorials - A utility to list your Amazon S3 buckets and optionally create a new one." +
                     "\n\nUsage: S3CreateAndList [bucket_name]" +
                     "\n - bucket_name: A valid, globally unique bucket name." +
                     "\n - If bucket_name isn't supplied, this utility simply lists your buckets.");
                   Environment.Exit(1);
               }
               return retval;
           }
   
           //
           // Method to get SSO credentials from the information in the shared config file.
           static AWSCredentials LoadSsoCredentials(string profile)
           {
               var chain = new CredentialProfileStoreChain();
               if (!chain.TryGetAWSCredentials(profile, out var credentials))
                   throw new Exception($"Failed to find the {profile} profile");
               return credentials;
           }
       }
   
       // Class to read the caller's identity.
       public static class Extensions
       {
           public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
           {
               var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
               return response.Arn;
           }
       }
   }
   ```

## 執行應用程式
<a name="s3-1-cross-run"></a>

1. 執行下列命令。

   ```
   dotnet run
   ```

1. 檢查輸出以查看您擁有的 Amazon S3 儲存貯體數量，如果有的話，及其名稱。

1. 選擇新 Amazon S3 儲存貯體的名稱。使用「dotnet-quicktour-s3-1-cross-」作為基礎，並為其新增唯一項目，例如 GUID 或您的名稱。請務必遵循儲存貯體名稱的規則，如 [Amazon S3 使用者指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)中的[儲存貯體命名規則](https://docs.aws.amazon.com/AmazonS3/latest/userguide/BucketRestrictions.html#bucketnamingrules)所述。

1. 執行下列命令，以您選擇的儲存貯體名稱取代 *amzn-s3-demo-bucket*。

   ```
   dotnet run amzn-s3-demo-bucket
   ```

1. 檢查輸出以查看建立的新儲存貯體。

## 清除
<a name="s3-1-cross-clean-up"></a>

執行本教學課程時，您建立了一些資源，此時可以選擇清除。
+ 如果您不想保留應用程式在先前步驟中建立的儲存貯體，請使用 Amazon S3 主控台將其刪除，網址為 https：//[https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/)。
+ 如果您不想保留 .NET 專案，請從開發環境中刪除該 `S3CreateAndList` 資料夾。

## 後續作業
<a name="s3-1-cross-next"></a>

返回[快速導覽功能表](quick-start.md)或直接前往[此快速導覽的結尾](quick-start-next-steps.md)。