Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob、Queue、File 和 Table。
Blob Storage 是什么?
Azure Blob Storage 是用来存放大量的像文本、图片、视频等非结构化数据的存储服务。我们可以在任何地方通过互联网协议 http 或者 https 访问 Blob Storage。简单说,就是把文件放在云上,给它一个 URL,通过这个 URL 来访问文件。这就涉及到一个问题:如何控制访问权限?答案是我们可以根据自己的需要,设置 Blob 对象是只能被自己访问,还是可以被所有人访问。
下面是 Blog Storage 典型的应用场景:
- 存储图片和文档,这些文件可以直接通过浏览器访问。
- 支持分布式访问,主要用于 cdn。
- 提供视频、音频流。
- 存储基本的文件备份和归档文件。
Azure Blob Storage 的结构
下图描述了 Blob Storage 的基本组织结构:
- Azure Storage Account:
Storage Account 是用来管理 Azure Storage 的一个命名空间,主要用来控制存储数据的访问权限和计费。对于 Blob、Queue、File 和 Table 这些 Azure 提供的存储服务的访问控制,都是通过 Storage Account 来进行的,所以要想使用 Blob Storage,首先需要创建你的 Storage Account。
- Container:
Container 中包含一组资源,所有的 Blob 都必须存在于Container中。一个 Storage Account 中可以包含无限个 Container,每个Container中也可以包含无限个Blob。需要注意的是 Container 的名字必须全部小写。
- Blob:
一个Blob 就代表一个文件。为了区分应用的场景及提升不同应用场景下存储的性能,又为 Blob 划分了不同的类型:block blobs, page blobs,append blobs。
- Block blobs 主要用来存储静态的文件,比如图片、电影和文档。
- Append blobs 与 block blobs 类似,但优化了 append 操作,主要的应用场景是存储日志文件。
- Page blobs 针对频繁的读写操作做了优化,如 Azure 上虚拟机的磁盘,就是使用的 page blobs
示例代码
//------------------------------------------------------------------------------ //MIT License //Copyright(c) 2017 Microsoft Corporation. All rights reserved. //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. //------------------------------------------------------------------------------ namespace storage_blobs_dotnet_quickstart { using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.IO; using System.Threading.Tasks; /// <summary> /// Azure Storage Quickstart Sample - Demonstrate how to upload, list, download, and delete blobs. /// /// Note: This sample uses the .NET asynchronous programming model to demonstrate how to call Blob storage using the /// storage client library's asynchronous API's. When used in production applications, this approach enables you to improve the /// responsiveness of your application. Calls to Blob storage are prefixed by the await keyword. /// /// Documentation References: /// - Azure Storage client library for .NET - https://docs.microsoft.com/dotnet/api/overview/azure/storage?view=azure-dotnet /// - Asynchronous Programming with Async and Await - http://msdn.microsoft.com/library/hh191443.aspx /// </summary> public static class Program { public static void Main() { Console.WriteLine("Azure Blob storage - .NET Quickstart sample"); Console.WriteLine(); ProcessAsync().GetAwaiter().GetResult(); Console.WriteLine("Press any key to exit the sample application."); Console.ReadLine(); } private static async Task ProcessAsync() { CloudStorageAccount storageAccount = null; CloudBlobContainer cloudBlobContainer = null; string sourceFile = null; string destinationFile = null; // 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 storageconnectionstring. // If the environment variable is created after the application is launched in a console or with Visual // Studio, the shell needs to be closed and reloaded to take the environment variable into account. string storageConnectionString = Environment.GetEnvironmentVariable("storageconnectionstring"); // Check whether the connection string can be parsed. if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { try { // 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 = cloudBlobClient.GetContainerReference("quickstartblobs" + Guid.NewGuid().ToString()); await cloudBlobContainer.CreateAsync(); Console.WriteLine("Created container '{0}'", cloudBlobContainer.Name); Console.WriteLine(); // Set the permissions so the blobs are public. BlobContainerPermissions permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; await cloudBlobContainer.SetPermissionsAsync(permissions); // 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"; 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); Console.WriteLine(); // 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); // List the blobs in the container. Console.WriteLine("Listing 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. Console.WriteLine(); // 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. destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt"); Console.WriteLine("Downloading blob to {0}", destinationFile); Console.WriteLine(); await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create); } catch (StorageException ex) { Console.WriteLine("Error returned from the service: {0}", ex.Message); } finally { Console.WriteLine("Press any key to delete the sample files and example container."); Console.ReadLine(); // Clean up resources. This includes the container and the two temp files. Console.WriteLine("Deleting the container and any blobs it contains"); if (cloudBlobContainer != null) { await cloudBlobContainer.DeleteIfExistsAsync(); } Console.WriteLine("Deleting the local source file and local downloaded files"); Console.WriteLine(); File.Delete(sourceFile); File.Delete(destinationFile); } } else { Console.WriteLine( "A connection string has not been defined in the system environment variables. " + "Add a environment variable named 'storageconnectionstring' with your storage " + "connection string as a value."); } } } }