開始使用 Azure Blob 儲存體和 Visual Studio 已連接服務 (ASP.NET Core)Get started with Azure Blob storage and Visual Studio connected services (ASP.NET Core)

提示

使用 Azure 儲存體總管來管理 Azure Blob 儲存體資源。Manage Azure Blob storage resources with Azure Storage Explorer. Azure 儲存體總管是一個 Microsoft 提供的免費獨立應用程式,可讓您管理 Azure Blob 儲存體資源Azure Storage Explorer is a free, standalone app from Microsoft that enables you to manage Azure Blob storage resources. 使用 Azure 儲存體總管,您能夠以視覺化方式建立、讀取、更新和刪除 Blob 容器和 Blob,以及管理對 Blob 容器和 Blob 的存取權。Using Azure Storage Explorer, you can visually create, read, update, and delete blob containers and blobs, as well as manage access to your blobs containers and blobs.

本文說明如何在您使用 Visual Studio 的已連線的服務功能建立或參考 ASP.NET Core 專案中的 Azure 儲存體帳戶之後,開始在 Visual Studio 使用 Azure Blob 儲存體。This article describes how to get started using Azure Blob storage in Visual Studio after you have created or referenced an Azure storage account in an ASP.NET Core project by using the Visual Studio Connected Services feature. 已連線的服務作業會安裝適當的 NuGet 套件,以存取專案中的 Azure 儲存體,並將儲存體帳戶的連接字串新增至您的專案設定檔。The Connected Services operation installs the appropriate NuGet packages to access Azure storage in your project and adds the connection string for the storage account to your project configuration files. (如需 Azure 儲存體的一般資訊,請參閱儲存體文件。)(See Storage documentation for general information about Azure Storage.)

Azure 二進位大型物件 (Microsoft Azure Blob) 儲存是一項儲存大量非結構化資料的服務,全球任何地方都可透過 HTTP 或 HTTPS 來存取這些資料。Azure Blob storage is a service for storing large amounts of unstructured data that can be accessed from anywhere in the world via HTTP or HTTPS. 單一 Blob 可以是任何大小。A single blob can be any size. Blob 可以是影像、音訊和視訊檔、原始資料及文件檔案。Blobs can be things like images, audio and video files, raw data, and document files. 本文描述如何在您於 ASP.NET Core 專案中使用 Visual Studio 的已連線的服務建立 Azure 儲存體帳戶之後,開始使用 Blob 儲存體。This article describes how to get started with blob storage after you create an Azure storage account by using the Visual Studio Connected Services in an ASP.NET Core project.

就像檔案在資料夾中一樣,儲存體 Blob 位於容器中。Just as files live in folders, storage blobs live in containers. 在您已建立 Blob 之後,您會在 Blob 中建立一個或多個容器。After you have created a blob, you create one or more containers in that blob. 例如,在稱為 "Scrapbook" 的 Blob 中,您可以建立稱為 "images" 的容器來儲存圖片,並建立稱為 "audio" 的容器來儲存音訊檔。For example, in a blob called "Scrapbook," you can create containers called "images" to store pictures and another called "audio" to store audio files. 建立容器之後,就可以將個別的檔案上傳至這些容器。After you create the containers, you can upload individual files to them. 請參閱快速入門:如需以程式設計方式處理 blob 的詳細資訊, 請使用 .net 上傳、下載及列出 blob。See Quickstart: Upload, download, and list blobs using .NET for more information on programmatically manipulating blobs.

某些 Azure 儲存體 API 是非同步的,本文章中的程式碼假設我們正在使用非同步方法。Some of the Azure Storage APIs are asynchronous, and the code in this article assumes async methods are being used. 如需詳細資訊,請參閱非同步程式設計See Asynchronous programming for more information.

在程式碼中存取 blob 容器Access blob containers in code

若要以程式設計方式存取 ASP.NET Core 專案中的 Blob,您需要加入下列程式碼 (若其不存在):To programmatically access blobs in ASP.NET Core projects, you need to add the following code if not already present:

  1. 加入必要的 using 陳述式:Add the necessary using statements:

    using Microsoft.Extensions.Configuration;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System.Threading.Tasks;
    using LogLevel = Microsoft.Extensions.Logging.LogLevel;
    
  2. 取得代表儲存體帳戶資訊的 CloudStorageAccount 物件。Get a CloudStorageAccount object that represents your storage account information. 使用下列程式碼,從 Azure 服務組態取得您的儲存體連接字串和儲存體帳戶資訊:Use the following code to get your storage connection string and storage account information from the Azure service configuration:

     CloudStorageAccount storageAccount = new CloudStorageAccount(
        new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
        "<storage-account-name>",
        "<access-key>"), true);
    
  3. 使用 CloudBlobClient 物件來取得儲存體帳戶中現有容器的 CloudBlobContainer 參考:Use a CloudBlobClient object to get a CloudBlobContainer reference to an existing container in your storage account:

    // Create a blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
    // Get a reference to a container named "mycontainer."
    CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
    

在程式碼中建立容器Create a container in code

您也可以使用 CloudBlobClient,藉由呼叫 CreateIfNotExistsAsync在儲存體帳戶中建立容器:You can also use the CloudBlobClient to create a container in your storage account by calling CreateIfNotExistsAsync:

// Create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Get a reference to a container named "my-new-container."
CloudBlobContainer container = blobClient.GetContainerReference("my-new-container");

// If "mycontainer" doesn't exist, create it.
await container.CreateIfNotExistsAsync();

若要讓所有人都能使用容器中的檔案,請將容器設定為公用容器:To make the files within the container available to everyone, set the container to be public:

await container.SetPermissionsAsync(new BlobContainerPermissions
{
    PublicAccess = BlobContainerPublicAccessType.Blob
});

將 Blob 上傳至容器Upload a blob into a container

若要將 Blob 檔案上傳至容器,請取得容器參考,並使用該參考來取得 Blob 參考。To upload a blob file into a container, get a container reference and use it to get a blob reference. 接著,呼叫 UploadFromStreamAsync 方法將所有資料串流上傳到該參考。Then upload any stream of data to that reference by calling the UploadFromStreamAsync method. 此作業會在 Blob 不存在的情況下建立 Blob,並覆寫現有的 Blob。This operation creates the blob if it's not already there, and overwrites an existing blob.

// Get a reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

// Create or overwrite the "myblob" blob with the contents of a local file
// named "myfile".
using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
{
    await blockBlob.UploadFromStreamAsync(fileStream);
}

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

若要列出容器中的 Blob,請先取得容器參考,然後再呼叫 ListBlobsSegmentedAsync 方法來擷取其中的 Blob 和/或目錄。To list the blobs in a container, first get a container reference, then call its ListBlobsSegmentedAsync method to retrieve the blobs and/or directories within it. 若要針對傳回的 IListBlobItem 存取一組豐富屬性與方法,請將其轉換成 CloudBlockBlobCloudPageBlobCloudBlobDirectory 物件。To access the rich set of properties and methods for a returned IListBlobItem, cast it to a CloudBlockBlob, CloudPageBlob, or CloudBlobDirectory object. 如果不知道 Blob 類型,可使用類型檢查來決定要將它轉換成何種類型。If you don't know the blob type, use a type check to determine which to cast it to.

BlobContinuationToken token = null;
do
{
    BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);
    token = resultSegment.ContinuationToken;

    foreach (IListBlobItem item in resultSegment.Results)
    {
        if (item.GetType() == typeof(CloudBlockBlob))
        {
            CloudBlockBlob blob = (CloudBlockBlob)item;
            Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
        }

        else if (item.GetType() == typeof(CloudPageBlob))
        {
            CloudPageBlob pageBlob = (CloudPageBlob)item;

            Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri);
        }

        else if (item.GetType() == typeof(CloudBlobDirectory))
        {
            CloudBlobDirectory directory = (CloudBlobDirectory)item;

            Console.WriteLine("Directory: {0}", directory.Uri);
        }
    }
} while (token != null);

請參閱快速入門:使用 .net上傳、下載及列出 blob, 以取得列出 blob 容器內容的其他方式。See Quickstart: Upload, download, and list blobs using .NET for other ways to list the contents of a blob container.

下載 BlobDownload a blob

若要下載 Blob,請先取得 Blob 的參考,然後呼叫 DownloadToStreamAsync 方法。To download a blob, first get a reference to the blob, then call the DownloadToStreamAsync method. 下列範例會使用 DownloadToStreamAsync 方法,將 Blob 內容傳送給資料流物件,您接著可將該物件儲存為本機檔案。The following example uses the DownloadToStreamAsync method to transfer the blob contents to a stream object that you can then save as a local file.

// Get a reference to a blob named "photo1.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("photo1.jpg");

// Save the blob contents to a file named "myfile".
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
    await blockBlob.DownloadToStreamAsync(fileStream);
}

請參閱快速入門:使用 .net上傳、下載及列出 blob, 以取得將 blob 另存為檔案的其他方式。See Quickstart: Upload, download, and list blobs using .NET for other ways to save blobs as files.

刪除 BlobDelete a blob

若要刪除 Blob,請先取得 Blob 的參考,然後呼叫 DeleteAsync 方法:To delete a blob, first get a reference to the blob, then call the DeleteAsync method:

// Get a reference to a blob named "myblob.txt".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob.txt");

// Delete the blob.
await blockBlob.DeleteAsync();

後續步驟Next steps

了解 Azure Blob 儲存體的基礎概念之後,請參考下列連結以了解有關更複雜的儲存工作。Now that you've learned the basics of Azure Blob storage, follow these links to learn about more complex storage tasks.