

第 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)

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

# 使用 的簡易 Windows 應用程式 適用於 .NET 的 AWS SDK
<a name="quick-start-s3-1-winvs"></a>

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

您將使用 Visual Studio 和 .NET Core 在 Windows 上執行此教學課程。如需設定開發環境的其他方式，請參閱 [安裝和設定 的工具鏈 適用於 .NET 的 AWS SDK](net-dg-dev-env.md)。

**在 Windows 上使用 Visual Studio 和 .NET Core 進行開發時需要：**
+ [Microsoft Visual Studio](https://visualstudio.microsoft.com/vs/)
+ Microsoft .NET Core 2.1、3.1 或更新版本

  在安裝最新版本的 Visual Studio 時，這通常是預設包含的。

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

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

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

1. 開啟 Visual Studio 並建立新的專案，使用**主控台應用程式**範本的 C\$1 版本；亦即，描述為「...用於建立可在 .NET... 上執行的命令列應用程式」。命名專案 `S3CreateAndList`。
**注意**  
請勿選擇主控台應用程式範本的 .NET Framework 版本，或者，如果您選擇，請務必使用 .NET Framework 4.7.2 或更新版本。

1. 載入新建立的專案後，選擇**工具**、**NuGet Package Manager**、**管理 NuGet Packages for Solution**。

1. 瀏覽下列 NuGet 套件，並將其安裝到專案中：`AWSSDK.S3`、`AWSSDK.SSO`、 `AWSSDK.SecurityToken`和 `AWSSDK.SSOOIDC`

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

1. 如果您想要從命令提示字元執行應用程式，請現在開啟命令提示字元，然後導覽至將包含建置輸出的資料夾。這通常類似 `S3CreateAndList\S3CreateAndList\bin\Debug\net6.0`，但取決於您的環境。

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

1. 在 `S3CreateAndList` 專案中，尋找並在 IDE 中開啟 `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;
           }
       }
   }
   ```

1. 建置應用程式。
**注意**  
如果您使用的是較舊版本的 Visual Studio，您可能會收到類似以下的建置錯誤：  
C\$1 7.0 不提供「功能」非同步主節點」。請使用語言版本 7.1 或更新版本。」  
如果您收到此錯誤，請將您的專案設定為使用較新版本的語言。這通常在專案屬性、**建置**、**進階**中完成。

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

1. 執行沒有命令列引數的應用程式。在命令提示字元 （如果您先前已開啟） 或從 IDE 中執行此操作。

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

1. 選擇新 Amazon S3 儲存貯體的名稱。使用「dotnet-quicktour-s3-1-winvs-」作為基礎，並為其新增唯一項目，例如 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*。

   ```
   S3CreateAndList amzn-s3-demo-bucket
   ```

   或者，如果您在 IDE 中執行應用程式，請選擇**專案**、**S3CreateAndList 屬性**、**偵錯**，然後在該處輸入儲存貯體名稱。

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

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

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

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

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