快速入门:通过 Xamarin 使用 Azure Blob 存储客户端库 v12Quickstart: Azure Blob storage client library v12 with Xamarin

通过 Xamarin 使用 Azure Blob 存储客户端库 v12 入门。Get started with the Azure Blob storage client library v12 with Xamarin. 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.

通过 Xamarin 使用 Azure Blob 存储客户端库 v12 完成以下操作:Use the Azure Blob storage client library v12 with Xamarin 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 device
  • 删除容器Delete a container

参考链接:Reference links:

备注

本文中所述的功能现在可用于具有分层命名空间的帐户。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

本部分逐步讲解如何准备项目,以便通过 Xamarin 使用 Azure Blob 存储客户端库 v12。This section walks you through preparing a project to work with the Azure Blob storage client library v12 with Xamarin.

创建项目Create the project

  1. 打开 Visual Studio 并创建一个空白窗体应用。Open Visual Studio and create a Blank Forms App.
  2. 将其命名为:BlobQuickstartV12Name it: BlobQuickstartV12

安装包Install the package

  1. 右键单击“解决方案资源管理器”窗格中的解决方案,并选择“为解决方案管理 NuGet 包”。Right-click your solution in the Solution Explorer pane and select Manage NuGet Packages for Solution.
  2. 搜索“Azure.Storage.Blobs”,将最新稳定版本安装到解决方案的所有项目中。Search for Azure.Storage.Blobs and install the latest stable version into all projects in your solution.

设置应用框架Set up the app framework

从“BlobQuickstartV12”目录执行以下操作:From the BlobQuickstartV12 directory:

  1. 在编辑器中打开 MainPage.xaml 文件Open up the MainPage.xaml file in your editor
  2. 删除 <ContentPage></ContentPage> 元素之间的所有内容,并将其替换为以下内容:Remove everything between the <ContentPage></ContentPage> elements and replace with the below:
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">

    <Button x:Name="uploadButton" Text="Upload Blob" Clicked="Upload_Clicked"  IsEnabled="False"/>
    <Button x:Name="listButton" Text="List Blobs" Clicked="List_Clicked"  IsEnabled="False" />
    <Button x:Name="downloadButton" Text="Download Blob" Clicked="Download_Clicked"  IsEnabled="False" />
    <Button x:Name="deleteButton" Text="Delete Container" Clicked="Delete_Clicked" IsEnabled="False" />

    <Label Text="" x:Name="resultsLabel" HorizontalTextAlignment="Center" Margin="0,20,0,0" TextColor="Red" />
        
</StackLayout>

从 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

复制连接字符串后,请将其设置为 MainPage.xaml.cs 文件中的类级别变量。After you have copied your connection string, set it to a class level variable in your MainPage.xaml.cs file. 打开 MainPaage.xaml.cs 并查找 storageConnectionString 变量。Open up MainPaage.xaml.cs and find the storageConnectionString variable. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

代码如下:Here's the code:

string storageConnectionString = "<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 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

这些示例代码片段演示了如何在 Xamarin.Forms 应用中使用适用于 .NET 的 Azure Blob 存储客户端库执行以下任务:These example code snippets show you how to perform the following tasks with the Azure Blob storage client library for .NET in a Xamarin.Forms app:

创建类级别变量Create class level variables

以下代码声明了几个类级别变量。The code below declares several class level variables. 在本示例的其余部分中,需要使用这些变量与 Azure Blob 存储通信。They needed to communicate to Azure Blob storage throughout the rest of this sample.

除了在配置存储连接字符串部分中设置的存储帐户的连接字符串外,还需要这些变量。These are in addition to the connection string for the storage account set in the Configure your storage connection string section.

请将此代码作为类级别变量添加到 MainPage.xaml.cs 文件中:Add this code as class level variables inside the MainPage.xaml.cs file:

string storageConnectionString = "{set in the Configure your storage connection string section}";
string fileName = $"{Guid.NewGuid()}-temp.txt";

BlobServiceClient client;
BlobContainerClient containerClient;
BlobClient blobClient;

创建容器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.

将以下代码添加到 MainPage.xaml.cs 文件中:Add this code to MainPage.xaml.cs file:

protected async override void OnAppearing()
{            
    string containerName = $"quickstartblobs{Guid.NewGuid()}";
    
    client = new BlobServiceClient(storageConnectionString);
    containerClient = await client.CreateBlobContainerAsync(containerName);

    resultsLabel.Text = "Container Created\n";

    blobClient = containerClient.GetBlobClient(fileName);

    uploadButton.IsEnabled = true;
}

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

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

  1. 创建文本的 MemoryStreamCreates a MemoryStream of text.
  2. 通过调用 BlobContainerClient 类的 UploadAsync 函数,将文本上传到 Blob,并向其传递文件名以及文本的 MemoryStreamUploads the text to a Blob by calling the UploadAsync function of the BlobContainerClient class, passing it in both the filename and the MemoryStream of text. 此方法将创建 Blob(如果该 Blob 尚不存在),或者覆盖 Blob(如果该 Blob 已存在)。This method creates the blob if it doesn't already exist, and overwrites it if it does.

将以下代码添加到 MainPage.xaml.cs 文件中:Add this code to the MainPage.xaml.cs file:

async void Upload_Clicked(object sender, EventArgs e)
{                                    
    using MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello World!"));

    await containerClient.UploadBlobAsync(fileName, memoryStream);

    resultsLabel.Text += "Blob Uploaded\n";

    uploadButton.IsEnabled = false;
    listButton.IsEnabled = true;
}

列出容器中的 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.

将以下代码添加到 MainPage.xaml.cs 文件中:Add this code to the MainPage.xaml.cs file:

async void List_Clicked(object sender, EventArgs e)
{            
    await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
    {
        resultsLabel.Text += blobItem.Name + "\n";                
    }

    listButton.IsEnabled = false;
    downloadButton.IsEnabled = true;
}

下载 BlobDownload blobs

通过调用 DownloadAsync 方法,下载以前创建的 blob。Download the previously created blob by calling the DownloadAsync method. 此示例代码先将 blob 的 Stream 表示形式复制到 MemoryStream 中,然后再复制到 StreamReader 中,以便显示文本。The example code copies the Stream representation of the blob first into a MemoryStream and then into a StreamReader so the text can be displayed.

将以下代码添加到 MainPage.xaml.cs 文件中:Add this code to the MainPage.xaml.cs file:

async void Download_Clicked(object sender, EventArgs e)
{
    BlobDownloadInfo downloadInfo = await blobClient.DownloadAsync();

    using MemoryStream memoryStream = new MemoryStream();
    
    await downloadInfo.Content.CopyToAsync(memoryStream);
    memoryStream.Position = 0;

    using StreamReader streamReader = new StreamReader(memoryStream);

    resultsLabel.Text += "Blob Contents: \n";
    resultsLabel.Text += await streamReader.ReadToEndAsync();
    resultsLabel.Text += "\n";

    downloadButton.IsEnabled = false;
    deleteButton.IsEnabled = true;
}

删除容器Delete a container

以下代码使用 DeleteAsync 来删除整个容器,从而清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the entire container by using DeleteAsync.

在删除 blob 和容器之前,应用首先会提示你进行确认。The app first prompts to confirm before it deletes the blob and container. 可以通过此机会验证是否已正确创建资源,然后再删除这些资源。This is a good chance to verify that the resources were created correctly, before they are deleted.

将以下代码添加到 MainPage.xaml.cs 文件中:Add this code to the MainPage.xaml.cs file:

async void Delete_Clicked(object sender, EventArgs e)
{            
    var deleteContainer = await Application.Current.MainPage.DisplayAlert("Delete Container",
        "You are about to delete the container proceeed?", "OK", "Cancel");

    if (deleteContainer == false)
        return;

    await containerClient.DeleteAsync();

    resultsLabel.Text += "Container Deleted";

    deleteButton.IsEnabled = false;
}

运行代码Run the code

应用启动时,会首先创建容器,就像所显示的那样。When the app starts, it will first create the container as it appears. 然后,你需要单击相关按钮以上传、列出、下载 Blob 以及删除容器。Then you will need to click the buttons in order to upload, list, download the blobs, and delete the container.

若要在 Windows 上运行应用,请按 F5。To run the app on Windows press F5. 若要在 Mac 上运行应用,请按 Cmd+Enter。To run the app on Mac press Cmd+Enter.

每次操作后,应用都会写入屏幕。The app writes to the screen after every operation. 应用的输出类似于以下示例:The output of the app is similar to the example below:

Container Created
Blob Uploaded
98d9a472-8e98-4978-ba4f-081d69d2e6f8-temp.txt
Blob Contents:
Hello World!
Container Deleted

在开始清理过程之前,请验证屏幕上 blob 内容的输出是否与上传的值匹配。Before you begin the clean-up process, verify the output of the blob's contents on screen match the value that was uploaded.

验证值后,确认删除容器的提示并完成演示。After you've verified the values, confirm the prompt to delete the container and finish the demo.

后续步骤Next steps

本快速入门介绍了如何通过 Xamarin 使用 Azure Blob 存储客户端库 v12 上传、下载和列出 blob。In this quickstart, you learned how to upload, download, and list blobs using Azure Blob storage client library v12 with Xamarin.

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