

的版本 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。本教程向您展示如何使用开发工具包列出您拥有的 [Amazon S3 桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)，并且可以选择创建新桶。

您将在 Windows 上使用 Visual Studio 和 .NET Core 完成本教程。有关配置开发环境的其它方法，请参阅[安装和配置您的工具链 适用于 .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)并[配置开发工具包身份验证](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. 加载新创建的项目后，选择 “**工具**”、“Pack NuGet age **Manager**”、“**管理解决方案 NuGet 包**”。

1. 浏览以下 NuGet 软件包并将其安装到项目中：`AWSSDK.S3``AWSSDK.SecurityToken`、`AWSSDK.SSO`、和 `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，则可能会遇到类似以下内容的构建错误：  
“Feature 'async main' is not available in C\$1 7.0. Please use language version 7.1 or greater.”  
如果您遇到此错误，请将项目设置为使用该语言的更高版本。这通常在项目属性**构建**、**高级**中完成。

## 运行应用程序
<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 中运行应用程序，请选择 “**项目**”、“**S3 CreateAndList 属性**”、“**调试**”，然后在那里输入存储桶名称。

1. 检查输出以查看创建的新存储桶。

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

执行本教程时，您创建了一些可选择在此时清理的资源。
+ 如果您不想保留应用程序在之前步骤中创建的存储桶，请使用位于的 Amazon S3 控制台将其删除[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)。