65.9K
CodeProject 正在变化。 阅读更多。
Home

Azure 存储账户(第二部分):使用 C# 上传文件到 Blob 存储

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2投票s)

2019年1月6日

CPOL

3分钟阅读

viewsIcon

20515

downloadIcon

255

如何使用 C# 上传文件到 Blob 存储

第 1 部分https://codeproject.org.cn/Articles/1273552/Azure-Storage-Account-Part-1-What-is-Blob

第 2 部分https://codeproject.org.cn/Articles/1273613/Azure-Storage-Account-Part-2-Upload-Files-in-Blob

Azure Blob logo

在上一篇文章Azure 存储帐户第 1 部分:什么是 Blob?中,我们了解了什么是 Azure 存储帐户,以及如何在 Blob 存储中管理文件,如何通过 Azure 门户上传和访问文件。在本模块中,我们将介绍如何在 Azure 存储帐户中的 Blob 中管理文件(上传、下载、删除、复制)。

我们将涵盖以下内容

  1. 存储帐户的连接字符串
  2. 设置 C# 项目以访问存储帐户
  3. 使用 C# 将文件上传到 Blob 存储
  4. 使用 C# 从 Blob 存储下载文件
  5. 使用 C# 删除 Blob
  6. 使用 C# 删除容器

开始吧!

1. 存储帐户的连接字符串

在上一模块中,我们介绍了 Azure 存储帐户的密钥和连接字符串。我们将在应用程序中使用这些连接string

在此之前,让我们了解如何获取存储帐户的连接string。从 Azure 门户转到存储帐户。从帐户列表中选择存储帐户。然后转到“访问密钥”部分。在这里,您将获得密钥和连接字符串。

access keys

复制其中一个连接字符串,我们将在应用程序中使用它。

2. 设置 C# 项目以访问存储帐户

现在创建一个 C# 控制台应用程序(您可以创建您选择的项目类型,Web 或 Windows)。

接下来,您必须从 NuGet 包管理器 (NPM) 安装 WindowsAzure.Storage 包。从工具 -> NuGet 包管理器 -> 包管理器控制台打开 NPM 控制台 (NPM)。

现在运行以下命令来安装 WindowsAzure.Storage

PM> Install-Package WindowsAzure.Storage -Version 9.3.3

之后,将在解决方案中添加几个引用

  • Microsoft.WindowsAzure.KeyVault.Core
  • Microsoft.Windows.Azure.Storage
  • Newtonsoft.Json

现在您的应用程序已准备好访问 Azure 存储帐户的文件。

请注意,从 9.4.0 开始,库已拆分为多个部分,例如 Microsoft.Azure.Storage.BlobMicrosoft.Azure.Storage.FileMicrosoft.Azure.Storage.QueueMicrosoft.Azure.Storage.Common

3. 使用 C# 将文件上传到 Blob 存储

首先,在应用程序中设置连接字符串。在 Web.ConfigappSettings 部分下设置它。

按照以下代码片段将文件上传到 Blob 存储。

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

private static string ConnectionSting
{
	get
	{
		return "your connection string";
	}
}

public static bool Upload()
{
	try
	{
		// set your container name
		var containerName = "your container name";
		
		// create object of storage account
		CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
		
		// create client of storage account
		CloudBlobClient client = storageAccount.CreateCloudBlobClient();
		
		// create the reference of your storage account
		CloudBlobContainer container = client.GetContainerReference(containerName);
		
		// check if the container exists or not in your account
		var isCreated = container.CreateIfNotExists();
		
		// set the permission to blob type
		container.SetPermissionsAsync(new BlobContainerPermissions 
                   { PublicAccess = BlobContainerPublicAccessType.Blob });

		// read the file to be uploaded
		using (FileStream fileStream = File.Open(@"C:\d\log.txt", FileMode.Open))
		{
			// create the memory steam which will be uploaded
			using (MemoryStream memoryStream = new MemoryStream())
			{
				// set the memory stream position to starting
				memoryStream.Position = 0;
				
				// copy file content to memory stream
				fileStream.CopyTo(memoryStream);

				var fileName  = "Test-log.txt";
				// create the object of blob which will be created
				// Test-log.txt is the name of the blob, pass your desired name
				CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

				// get the mime type of the file
				string mimeType = "application/unknown";
				string ext = (fileName.Contains(".")) ? 
                            System.IO.Path.GetExtension(fileName).ToLower() : "." + fileName;
				Microsoft.Win32.RegistryKey regKey = 
                            Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
				if (regKey != null && regKey.GetValue("Content Type") != null) 
                            mimeType = regKey.GetValue("Content Type").ToString();

				// set the memory stream position to zero again
				// this is one of the important stage, If you miss this step, 
				// your blob will be created but size will be 0 byte
				memoryStream.ToArray();
				memoryStream.Seek(0, SeekOrigin.Begin);

				// set the mime type
				blob.Properties.ContentType = mimeType;
				
				// upload the stream to blob
				blob.UploadFromStream(memoryStream);
			}
		}
		
		return true;
	}
	catch (Exception ex)
	{
		throw;
	}
}

现在转到 Azure 门户并刷新 Blob blade,您将在那里找到您的文件。

4. 使用 C# 从 Blob 存储下载文件

现在上传文件后,是时候将文件作为 stream 取回了。

为此,请按照以下代码片段

public static MemoryStream Download()
{
	var containerName  = "your container name";
	var blobName = "blob name that you have set";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);

	// get a particular blob within that container
	CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

	// get list of all blobs in the container
	var allBlobs = container.ListBlobs();

	// convert the blob to memorystream
	MemoryStream memStream = new MemoryStream();
	blockBlob.DownloadToStream(memStream);
	return memStream;
}

现在您可以从内存流创建文件,或者可以从 Web API 传递该流。

5. 使用 C# 删除 Blob

要删除 Blob,过程大致相同。创建存储帐户和容器的实例。然后,检查 Blob 是否存在。如果存在,则删除它。 Microsoft 有一个内置函数来删除 Blob。 CloudBlockBlob.DeleteIfExists

public static bool DeleteBlob()
{
	var containerName  = "your container name";
	var blobName = "blob name that you have set";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);

	// get a particular blob within that container
	CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
	
	// delete the blob and return bool
	return blockBlob.DeleteIfExists()
}

要删除容器的所有文件,您需要循环访问容器的所有 Blob 并单独删除它们。

6. 使用 C# 删除容器

要删除整个容器,请按照以下代码片段。使用 CloudBlobContainer.Delete(AccessCondition, BlobRequestOptions, OperationContext) 方法删除容器。

public static bool DeleteContainer()
{
	var containerName  = "your container name";
	var blobName = "blob name that you have set";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);
	
	// delete container
	container.Delete();
}

零件

© . All rights reserved.