快速入门:适用于 .NET 的 Azure Blob 存储客户端库 v12Quickstart: Azure Blob storage client library v12 for .NET

适用于 .NET 的 Azure Blob 存储客户端库 v12 入门。Get started with the Azure Blob storage client library v12 for .NET. Azure Blob 存储是 Azure 的适用于云的对象存储解决方案。Azure Blob storage is Azure's object storage solution for the cloud. 请按照步骤操作,安装程序包并试用基本任务的示例代码。Follow steps to install the package and try out example code for basic tasks. Blob 存储最适合存储巨量的非结构化数据。Blob storage is optimized for storing massive amounts of unstructured data.

备注

若要使用之前的 SDK 版本入门,请参阅快速入门:适用于 .NET 的 Azure Blob 存储客户端库To get started with the previous SDK version, see Quickstart: Azure Blob storage client library for .NET.

使用适用于 .NET 的 Azure Blob 存储客户端库 v12 完成以下操作:Use the Azure Blob storage client library v12 for .NET to:

  • 创建容器Create a container
  • 将 blob 上传到 Azure 存储Upload a blob to Azure Storage
  • 列出容器中所有的 blobList all of the blobs in a container
  • 将 blob 下载到本地计算机Download the blob to your local computer
  • 删除容器Delete a container

API 参考文档 | 库源代码 | 包 (NuGet) | 示例API reference documentation | Library source code | Package (NuGet) | Samples

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。The features described in this article are now available to accounts that have a hierarchical namespace. 若要查看限制,请参阅 Azure Data Lake Storage Gen2 中可用的 Blob 存储功能一文。To review limitations, see the Blob storage features available in Azure Data Lake Storage Gen2 article.

先决条件Prerequisites

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 .NET 的 Azure Blob 存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Blob storage client library v12 for .NET.

创建项目Create the project

创建名为 BlobQuickstartV12 的 .NET Core 应用程序 。Create a .NET Core application named BlobQuickstartV12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 BlobQuickstartV12 的新控制台应用 。In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name BlobQuickstartV12. 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.csThis command creates a simple "Hello World" C# project with a single source file: Program.cs.

    dotnet new console -n BlobQuickstartV12
    
  2. 切换到新创建的 BlobQuickstartV12 目录 。Switch to the newly created BlobQuickstartV12 directory.

    cd BlobQuickstartV12
    
  3. 在 BlobQuickstartV12 目录中,创建名为 data 的另一个目录 。In side the BlobQuickstartV12 directory, create another directory called data. 将在这里创建和存储 blob 数据文件。This is where the blob data files will be created and stored.

    mkdir data
    

安装包Install the package

仍在应用程序目录中时,使用 dotnet add package 命令安装适用于 .NET 包的 Azure Blob 存储客户端库。While still in the application directory, install the Azure Blob storage client library for .NET package by using the dotnet add package command.

dotnet add package Azure.Storage.Blobs

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 在编辑器中打开 Program.cs 文件Open the Program.cs file in your editor
  2. 删除 Console.WriteLine("Hello World!"); 语句Remove the Console.WriteLine("Hello World!"); statement
  3. 添加 using 指令Add using directives
  4. 更新 Main 方法声明以支持异步代码Update the Main method declaration to support async code

代码如下:Here's the code:

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
using System.Threading.Tasks;

namespace BlobQuickstartV12
{
    class Program
    {
        static async Task Main()
        {
        }
    }
}

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure Blob 存储最适合存储巨量的非结构化数据。Azure Blob storage is optimized for storing massive amounts of unstructured data. 非结构化数据是不遵循特定数据模型或定义的数据(如文本或二进制数据)。Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob 存储提供了三种类型的资源:Blob storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的容器A container in the storage account
  • 容器中的 blobA blob in the container

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

Blob 存储体系结构的图示

使用以下 .NET 类与这些资源进行交互:Use the following .NET classes to interact with these resources:

  • BlobServiceClientBlobServiceClient 类可用于操纵 Azure 存储资源和 blob 容器。BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • BlobContainerClientBlobContainerClient 类可用于操纵 Azure 存储容器及其 blob。BlobContainerClient: The BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClientBlobClient 类可用于操纵 Azure 存储 blob。BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.
  • BlobDownloadInfoBlobDownloadInfo 类表示从下载 blob 返回的属性和内容。BlobDownloadInfo: The BlobDownloadInfo class represents the properties and content returned from downloading a blob.

代码示例Code examples

这些示例代码片段演示如何使用适用于 .NET 的 Azure Blob 存储客户端库执行以下步骤:These example code snippets show you how to perform the following with the Azure Blob storage client library for .NET:

获取连接字符串Get the connection string

下面的代码从配置存储连接字符串部分中创建的环境变量中检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

Main 方法内添加此代码:Add this code inside the Main method:

Console.WriteLine("Azure Blob storage v12 - .NET quickstart sample\n");

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable on the machine
// running the application called AZURE_STORAGE_CONNECTION_STRING. If the
// environment variable is created after the application is launched in a
// console or with Visual Studio, the shell or application needs to be closed
// and reloaded to take the environment variable into account.
string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

创建容器Create a container

确定新容器的名称。Decide on a name for the new container. 以下代码将 GUID 值追加到容器名称,确保其是唯一的。The code below appends a GUID value to the container name to ensure that it is unique.

重要

容器名称必须为小写。Container names must be lowercase. 有关命名容器和 Blob 的详细信息,请参阅命名和引用容器、Blob 和元数据For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

创建 BlobServiceClient 类的实例。Create an instance of the BlobServiceClient class. 然后,调用 CreateBlobContainerAsync 方法在存储帐户中创建容器。Then, call the CreateBlobContainerAsync method to create the container in your storage account.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

//Create a unique name for the container
string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

将 blob 上传到容器中Upload blobs to a container

以下代码片段:The following code snippet:

  1. 在本地 data 目录中创建文本文件 。Creates a text file in the local data directory.
  2. 对在创建容器部分创建的容器调用 GetBlobClient 方法,获取对 BlobClient 对象的引用。Gets a reference to a BlobClient object by calling the GetBlobClient method on the container from the Create a container section.
  3. 通过调用 UploadAsync 方法将本地文本文件上传到 blob。Uploads the local text file to the blob by calling the UploadAsync method. 此方法将创建 Blob(如果该 Blob 尚不存在),或者覆盖 Blob(如果该 Blob 已存在)。This method creates the blob if it doesn't already exist, and overwrites it if it does.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

列出容器中的 BlobList the blobs in a container

通过调用 GetBlobsAsync 方法,列出容器中的 blob。List the blobs in the container by calling the GetBlobsAsync method. 在这种情况下,只向容器添加了一个 blob,因此列表操作只返回那个 blob。In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

Console.WriteLine("Listing blobs...");

// List all blobs in the container
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
    Console.WriteLine("\t" + blobItem.Name);
}

下载 BlobDownload blobs

通过调用 DownloadAsync 方法,下载以前创建的 blob。Download the previously created blob by calling the DownloadAsync method. 示例代码将向文件名添加后缀“DOWNLOADED”,这样你就可以在本地文件系统中看到这两个文件。The example code adds a suffix of "DOWNLOADED" to the file name so that you can see both files in local file system.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// Download the blob to a local file
// Append the string "DOWNLOAD" before the .txt extension 
// so you can compare the files in the data directory
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");

Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();

using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
    await download.Content.CopyToAsync(downloadFileStream);
    downloadFileStream.Close();
}

删除容器Delete a container

以下代码使用 DeleteAsync 来删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the entire container by using DeleteAsync. 它还会删除由应用创建的本地文件。It also deletes the local files created by the app.

在删除 blob、容器和本地文件之前,应用会调用 Console.ReadLine 以暂停并等待用户输入。The app pauses for user input by calling Console.ReadLine before it deletes the blob, container, and local files. 可以通过这种方式验证是否已正确创建资源,然后再删除该资源。This is a good chance to verify that the resources were actually created correctly, before they are deleted.

将此代码添加到 Main 方法的末尾:Add this code to the end of the Main method:

// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();

Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();

Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);

Console.WriteLine("Done");

运行代码Run the code

此应用在本地 data 文件夹中创建测试文件,并将其上传到 Blob 存储。This app creates a test file in your local data folder and uploads it to Blob storage. 然后,该示例会列出容器中的 blob,并使用新名称下载文件,这样便可对新旧文件进行对比。The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.

导航到应用程序目录,然后生成并运行应用程序。Navigate to your application directory, then build and run the application.

dotnet build
dotnet run

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Blob storage v12 - .NET quickstart sample

Uploading to Blob storage as blob:
         https://mystorageacct.blob.core.chinacloudapi.cn/quickstartblobs60c70d78-8d93-43ae-954d-8322058cfd64/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Listing blobs...
        quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Downloading blob to
        ./data/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31DOWNLOADED.txt

Press any key to begin clean up
Deleting blob container...
Deleting the local source and downloaded files...
Done

在开始清理过程之前,请在“data”文件夹中查看这两个文件 。Before you begin the clean up process, check your data folder for the two files. 可以打开它们,然后就会观察到它们完全相同。You can open them and observe that they are identical.

验证文件后,按 Enter 键以删除测试文件并完成演示 。After you've verified the files, press the Enter key to delete the test files and finish the demo.

后续步骤Next steps

本快速入门介绍了如何使用 .NET 上传、下载和列出 Blob。In this quickstart, you learned how to upload, download, and list blobs using .NET.

若要查看 Blob 存储示例应用,请继续执行以下操作:To see Blob storage sample apps, continue to: