簡單的基於 Windows 的應用程序使用 AWS SDK for .NET - AWS SDK for .NET

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

簡單的基於 Windows 的應用程序使用 AWS SDK for .NET

本教程使用 AWS SDK for .NET 視窗與視覺工作室和 .NET 核心。本教學說明如何使用開發套件列出您擁有的 Amazon S3 儲存貯體,並選擇性地建立儲存貯體。

您將使用 Visual Studio 和 .NET Core 在 Windows 上執行此教學課程。如需設定開發環境的其他方法,請參閱安裝和設定您的工具鏈

需要在視窗上使用視覺工作室和 .NET 核心進行開發:

  • Microsoft .NET Core 2.1、3.1 或更新版本

    安裝最新版本的 Visual Studio 時,這通常會包含在預設情況下。

注意

在使用這些教學課程之前,您必須先安裝工具鏈設定 SDK 驗證

步驟

建立專案

  1. 打開 Visual Studio 並創建一個使用 C# 版本的控制台應用程序模板的新項目; 也就是說明:「... 創建可以在 .NET 上運行的命令行應用程序...」。命名專案 S3CreateAndList

    注意

    請勿選擇主控台應用程式範本的 .NET 架構版本,或者,如果選擇,請務必使用 .NET Framework 4.7.2 或更新版本。

  2. 載入新建立的專案後,選擇 [工具]、[P NuGetackage 件管理員]、[管理解決方案的 NuGet 套件]。

  3. 瀏覽以下 NuGet 套件並將其安裝到專案中:AWSSDK.S3AWSSDK.SecurityTokenAWSSDK.SSO、和 AWSSDK.SSOOIDC

    這個過程從 NuGet 軟件包管理器安裝軟件NuGet 包。因為我們確切地知道本教程需要什麼 NuGet 包,所以我們現在可以執行此步驟。在開發過程中,所需的軟件包也很常見。發生這種情況時,請按照類似的過程進行安裝。

  4. 如果您打算從命令提示符運行應用程序,請立即打開命令提示符並導航到將包含構建輸出的文件夾。這通常是類似的S3CreateAndList\S3CreateAndList\bin\Debug\net6.0,但將取決於您的環境。

建立程式碼

  1. S3CreateAndList 專案中,尋找並在 IDE 中開啟 Program.cs

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

    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; } } }
  3. 建置應用程式。

    注意

    如果您使用的是舊版 Visual Studio,您可能會收到類似下列內容的建置錯誤:

    「功能 '異步主' 在 C#7.0 中不可用。請使用 7.1 或更高版本的語言。」

    如果出現此錯誤,請將您的專案設定為使用較新版本的語言。這通常是在項目屬性,構建高級完成。

執行應用程式

  1. 執行沒有命令列引數的應用程式。在命令提示符(如果您之前打開了命令提示符)或從 IDE 執行此操作。

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

  3. 為新的 Amazon S3 儲存貯體選擇一個名稱。使用「dotnet-quicktour-s3-1-winvs-」作為基礎,並添加一些獨特的東西,例如 GUID 或您的名稱。請務必遵循儲存貯體名稱的規則,如 Amazon S3 使用者指南的「儲存貯體命名規則」中所述。

  4. 再次執行應用程式,這次提供存儲存貯體名稱。

    在命令列中,將下列命令中的 BUCKET-NAME 取代為您選擇的值區的名稱。

    S3CreateAndList BUCKET-NAME

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

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

清除

在執行本教學課程時,您建立了一些資源,您可以選擇此時進行清理。

後續作業

返回快速導覽菜單或直接前往此快速導覽的結尾