您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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

适用于 .NET 的 Azure Blob 存储客户端库入门。Get started with the Azure Blob Storage client library for .NET. Azure Blob 存储是 Microsoft 提供的适用于云的对象存储解决方案。Azure Blob Storage is Microsoft'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.

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

  • 创建容器Create a container
  • 设置容器权限Set permissions on a container
  • 在 Azure 存储中创建 blobCreate a blob in Azure Storage
  • 将 blob 下载到本地计算机Download the blob to your local computer
  • 列出容器中所有的 blobList all of the blobs in a container
  • 删除容器Delete a container

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

先决条件Prerequisites

设置Setting up

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

创建项目Create the project

首先,创建名为 blob-quickstart 的 .NET Core 应用程序 。First, create a .NET Core application named blob-quickstart.

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

    dotnet new console -n blob-quickstart
    
  2. 切换到新建的 blob-quickstart 文件夹,并生成应用以验证一切是否正常 。Switch to the newly created blob-quickstart folder and build the app to verify that all is well.

    cd blob-quickstart
    
    dotnet build
    

内部版本的预期输出应如下所示:The expected output from the build should look something like this:

C:\QuickStarts\blob-quickstart> dotnet build
Microsoft (R) Build Engine version 16.0.450+ga8dc7f1d34 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 44.31 ms for C:\QuickStarts\blob-quickstart\blob-quickstart.csproj.
  blob-quickstart -> C:\QuickStarts\blob-quickstart\bin\Debug\netcoreapp2.1\blob-quickstart.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.08

安装包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 Microsoft.Azure.Storage.Blob

设置应用框架Set up the app framework

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

  1. 在编辑器中打开 Program.cs 文件Open the Program.cs file in your editor
  2. 删除 Console.WriteLine 语句 Remove the Console.WriteLine statement
  3. 添加 using 指令 Add using directives
  4. 创建 ProcessAsync 方法,示例的 main 代码将保留在其中 Create a ProcessAsync method where the main code for the example will reside
  5. 以异步方式从 Main 调用 ProcessAsync 方法 Asynchronously call the ProcessAsync method from Main

代码如下:Here's the code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;

namespace blob_quickstart
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Azure Blob Storage - .NET quickstart sample\n");

            // Run the examples asynchronously, wait for the results before proceeding
            ProcessAsync().GetAwaiter().GetResult();

            Console.WriteLine("Press any key to exit the sample application.");
            Console.ReadLine();
        }

        private static async Task ProcessAsync()
        {
        }
    }
}

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

此示例应用程序需对存储帐户访问进行身份验证。The sample application needs to authenticate access to your storage account. 若要进行身份验证,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authenticate, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 导航到 Azure 门户Navigate 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.

添加环境变量后,可能需要重启任何正在运行的、需要读取环境变量的程序。After you add the environment variable, you may need to restart any running programs that will need to read the environment variable. 例如,如果使用 Visual Studio 作为编辑器,请在运行示例之前重启 Visual Studio。For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

WindowsWindows

setx STORAGE_CONNECTION_STRING "<yourconnectionstring>"

LinuxLinux

export STORAGE_CONNECTION_STRING="<yourconnectionstring>"

MacOSMacOS

export STORAGE_CONNECTION_STRING="<yourconnectionstring>"

对象模型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 a container

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

Blob 存储体系结构的图示

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

  • CloudStorageAccountCloudStorageAccount 类表示你的 Azure 存储帐户。CloudStorageAccount: The CloudStorageAccount class represents your Azure storage account. 借助此类,可使用帐户访问密钥授予对 Blob 存储的访问权限。Use this class to authorize access to Blob storage using your account access keys.
  • CloudBlobClientCloudBlobClient 类提供对代码中 Blob 服务的访问点。CloudBlobClient: The CloudBlobClient class provides a point of access to the Blob service in your code.
  • CloudBlobContainerCloudBlobContainer 类表示代码中的 blob 容器。CloudBlobContainer: The CloudBlobContainer class represents a blob container in your code.
  • CloudBlockBlobCloudBlockBlob 对象表示代码中的块 blob。CloudBlockBlob: The CloudBlockBlob object represents a block blob in your code. 块 Blob 由可以分别管理的数据块构成。Block blobs are made up of blocks of data that can be managed individually.

代码示例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:

验证客户端Authenticate the client

以下代码检查环境变量是否包含一个连接字符串,该字符串在经过分析后可以创建一个指向存储帐户的 CloudStorageAccount 对象。The code below checks that the environment variable contains a connection string that can be parsed to create a CloudStorageAccount object pointing to the storage account. 若要检查连接字符串是否有效,请使用 TryParse 方法。To check that the connection string is valid, use the TryParse method. 如果 TryParse 成功,它会初始化 storageAccount 变量并返回 trueIf TryParse is successful, it initializes the storageAccount variable and returns true.

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

// 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 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 storageConnectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

// Check whether the connection string can be parsed.
CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
{
    // If the connection string is valid, proceed with operations against Blob
    // storage here.
    // ADD OTHER OPERATIONS HERE
}
else
{
    // Otherwise, let the user know that they need to define the environment variable.
    Console.WriteLine(
        "A connection string has not been defined in the system environment variables. " +
        "Add an environment variable named 'STORAGE_CONNECTION_STRING' with your storage " +
        "connection string as a value.");
    Console.WriteLine("Press any key to exit the application.");
    Console.ReadLine();
}

备注

若要执行本文中的其余操作,请使用以下部分中的代码片段替换上述代码中的 // ADD OTHER OPERATIONS HERE 。To perform the rest of the operations in this article, replace // ADD OTHER OPERATIONS HERE in the code above with the code snippets in the following sections.

创建容器Create a container

若要创建容器,请先创建 CloudBlobClient 对象的实例,该对象指向存储帐户中的 Blob 存储。To create the container, first create an instance of the CloudBlobClient object, which points to Blob storage in your storage account. 接下来,请创建 CloudBlobContainer 对象的实例,然后创建容器。Next, create an instance of the CloudBlobContainer object, then create the container.

在此示例中,代码调用 CreateAsync 方法来创建容器。In this case, the code calls the CreateAsync method to create the container. GUID 值会追加到容器名称,确保其是唯一的。A GUID value is appended to the container name to ensure that it is unique. 在生产环境中,通常情况下,首选使用 CreateIfNotExistsAsync 方法来创建容器的前提是该方法不存在。In a production environment, it's often preferable to use the CreateIfNotExistsAsync method to create a container only if it does not already exist.

重要

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

// Create the CloudBlobClient that represents the 
// Blob storage endpoint for the storage account.
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

// Create a container called 'quickstartblobs' and 
// append a GUID value to it to make the name unique.
CloudBlobContainer cloudBlobContainer = 
    cloudBlobClient.GetContainerReference("quickstartblobs" + 
        Guid.NewGuid().ToString());
await cloudBlobContainer.CreateAsync();

设置容器权限Set permissions on a container

设置容器权限,使容器中的所有 blob 都是公共的。Set permissions on the container so that any blobs in the container are public. 如果某个 Blob 是公开的,则任何客户端都可以对其进行匿名访问。If a blob is public, it can be accessed anonymously by any client.

// Set the permissions so the blobs are public.
BlobContainerPermissions permissions = new BlobContainerPermissions
{
    PublicAccess = BlobContainerPublicAccessType.Blob
};
await cloudBlobContainer.SetPermissionsAsync(permissions);

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

以下代码片段通过针对前面部分创建的容器调用 GetBlockBlobReference 方法,获取 CloudBlockBlob 对象的引用。The following code snippet gets a reference to a CloudBlockBlob object by calling the GetBlockBlobReference method on the container created in the previous section. 然后,它会通过调用 UploadFromFileAsync 方法将所选本地文件上传到 blob。It then uploads the selected local file to the blob by calling the UploadFromFileAsync method. 此方法将创建 Blob(如果该 Blob 尚不存在),或者覆盖 Blob(如果该 Blob 已存在)。This method creates the blob if it doesn't already exist, and overwrites it if it does.

// Create a file in your local MyDocuments folder to upload to a blob.
string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
string sourceFile = Path.Combine(localPath, localFileName);
// Write text to the file.
File.WriteAllText(sourceFile, "Hello, World!");

Console.WriteLine("Temp file = {0}", sourceFile);
Console.WriteLine("Uploading to Blob storage as blob '{0}'", localFileName);

// Get a reference to the blob address, then upload the file to the blob.
// Use the value of localFileName for the blob name.
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName);
await cloudBlockBlob.UploadFromFileAsync(sourceFile);

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

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

如果一次调用需要返回的 Blob 数过多(默认为超过 5000 个),则 ListBlobsSegmentedAsync 方法会返回总结果集的一部分和一个继续令牌。If there are too many blobs to return in one call (by default, more than 5000), then the ListBlobsSegmentedAsync method returns a segment of the total result set and a continuation token. 若要检索下一部分的 Blob,请提供前一调用返回的继续令牌,依此类推,直至继续令牌为 null。To retrieve the next segment of blobs, you provide in the continuation token returned by the previous call, and so on, until the continuation token is null. 继续令牌为 null 表明已检索所有 Blob。A null continuation token indicates that all of the blobs have been retrieved. 代码演示如何根据最佳做法使用继续令牌。The code shows how to use the continuation token for the sake of best practices.

// List the blobs in the container.
Console.WriteLine("List blobs in container.");
BlobContinuationToken blobContinuationToken = null;
do
{
    var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);
    // Get the value of the continuation token returned by the listing call.
    blobContinuationToken = results.ContinuationToken;
    foreach (IListBlobItem item in results.Results)
    {
        Console.WriteLine(item.Uri);
    }
} while (blobContinuationToken != null); // Loop while the continuation token is not null.

下载 BlobDownload blobs

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

// Download the blob to a local file, using the reference created earlier.
// Append the string "_DOWNLOADED" before the .txt extension so that you 
// can see both files in MyDocuments.
string destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
Console.WriteLine("Downloading blob to {0}", destinationFile);
await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);

删除容器Delete a container

以下代码使用 CloudBlobContainer.DeleteAsync 来删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the entire container using CloudBlobContainer.DeleteAsync. 也可根据需要删除本地文件。You can also delete the local files if you like.

Console.WriteLine("Press the 'Enter' key to delete the example files, " +
    "example container, and exit the application.");
Console.ReadLine();
// Clean up resources. This includes the container and the two temp files.
Console.WriteLine("Deleting the container");
if (cloudBlobContainer != null)
{
    await cloudBlobContainer.DeleteIfExistsAsync();
}
Console.WriteLine("Deleting the source, and downloaded files");
File.Delete(sourceFile);
File.Delete(destinationFile);

运行代码Run the code

此应用在本地 MyDocuments 文件夹中创建一个测试文件,并将其上传到 Blob 存储。This app creates a test file in your local MyDocuments 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.

如果使用 Visual Studio 作为编辑器,可以按 F5 运行应用程序。If you are using Visual Studio as your editor, you can press F5 to run.

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

dotnet build
dotnet run

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

Azure Blob storage - .NET Quickstart example

Created container 'quickstartblobs33c90d2a-eabd-4236-958b-5cc5949e731f'

Temp file = C:\Users\myusername\Documents\QuickStart_c5e7f24f-a7f8-4926-a9da-96
97c748f4db.txt
Uploading to Blob storage as blob 'QuickStart_c5e7f24f-a7f8-4926-a9da-9697c748f
4db.txt'

Listing blobs in container.
https://storagesamples.blob.core.windows.net/quickstartblobs33c90d2a-eabd-4236-
958b-5cc5949e731f/QuickStart_c5e7f24f-a7f8-4926-a9da-9697c748f4db.txt

Downloading blob to C:\Users\myusername\Documents\QuickStart_c5e7f24f-a7f8-4926
-a9da-9697c748f4db_DOWNLOADED.txt

Press any key to delete the example files and example container.

Enter 键时,应用程序会删除存储容器和文件。When you press the Enter key, the application deletes the storage container and the files. 在删除之前,请在 MyDocuments 文件夹中查看这两个文件。Before you delete them, check your MyDocuments folder for the two files. 可以打开它们,然后就会观察到它们完全相同。You can open them and observe that they are identical. 从控制台窗口复制 Blob 的 URL,将其粘贴到浏览器中,查看 Blob 的内容。Copy the blob's URL from the console window and paste it into a browser to view the contents of the blob.

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

后续步骤Next steps

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

若要了解如何创建一个 Web 应用,以便将映像上传到 Blob 存储,请继续学习:To learn how to create a web app that uploads an image to Blob storage, continue to: