[转]windows azure How to use Blob storage from .NET
本文转自:http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/?rnd=1
Overview
This guide will demonstrate how to perform common scenarios using the Azure Blob storage service. The samples are written in C# and use the Azure Storage Client Library for .NET. The scenarios covered include uploading, listing, downloading, and deleting blobs.
NOTE:
This guide targets the Azure .NET Storage Client Library 2.x and above. The recommended version is Storage Client Library 4.x, which is available via NuGet or as part of the Azure SDK for .NET. See Programmatically access Blob storage below for more details on obtaining the Storage Client Library.
What is Blob Storage
Azure Blob storage is a service for storing large amounts of unstructured data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.
Common uses of Blob storage include:
- Serving images or documents directly to a browser
- Storing files for distributed access
- Streaming video and audio
- Performing secure backup and disaster recovery
- Storing data for analysis by an on-premises or Azure-hosted service
Blob Service Concepts
The Blob service contains the following components:
Storage Account: All access to Azure Storage is done through a storage account. See Azure Storage Scalability and Performance Targets for details about storage account capacity.
Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs.
Blob: A file of any type and size. There are two types of blobs that can be stored in Azure Storage: block and page blobs. Most files are block blobs. A single block blob can be up to 200 GB in size. This tutorial uses block blobs. Page blobs, another blob type, can be up to 1 TB in size, and are more efficient when ranges of bytes in a file are modified frequently. For more information about blobs, see [Understanding Block Blobs and Page Blobs][].
URL format: Blobs are addressable using the following URL format: http://
<storage account>
.blob.core.windows.net/<container>
/<blob>
The following example URL could be used to address one of the blobs in the diagram above:
http://sally.blob.core.windows.net/movies/MOV1.AVI
Create an Azure Storage account
To use Azure storage, you'll need a storage account. You can create a storage account by following these steps. (You can also create a storage account by using the Azure service management client library or the service management REST API.)
Log into the Azure Management Portal.
At the bottom of the navigation pane, click NEW.
Click DATA SERVICES, then STORAGE, and then click QUICK CREATE.
In URL, type a subdomain name to use in the URI for the storage account. The entry can contain from 3-24 lowercase letters and numbers. This value becomes the host name within the URI that is used to address Blob, Queue, or Table resources for the subscription.
Choose a Region/Affinity Group in which to locate the storage. If you will be using storage from your Azure application, select the same region where you will deploy your application.
Optionally, you can select the type of replication you desire for your account. Geo-redundant replication is the default and provides maximum durability. For more details on replication options, see Azure Storage Redundancy Options and the Azure Storage Team Blog.
Click CREATE STORAGE ACCOUNT.
Setup a storage connection string
The Azure Storage Client Library for .NET supports using a storage connection string to configure endpoints and credentials for accessing storage services. We recommend that you maintain your storage connection string in a configuration file, rather than hard-coding it into your application. You have two options for saving your connection string:
- If your application runs in an Azure cloud service, save your connection string using the Azure service configuration system (
*.csdef
and*.cscfg
files). - If your application runs on Azure virtual machines, or if you are building .NET applications that will run outside of Azure, save your connection string using the .NET configuration system (e.g.
web.config
orapp.config
file).
Later on in this guide, we will show how to retrieve your connection string from your code.
Configuring your connection string from an Azure cloud service
Azure Cloud Services has a unique service configuration mechanism that enables you to dynamically change configuration settings from the Azure Management Portal without redeploying your application.
To configure your connection string in the Azure service configuration:
Within the Solution Explorer of Visual Studio, in the Roles folder of your Azure Deployment Project, right-click your web role or worker role and click Properties.
Click the Settings tab and press the Add Setting button.
A new Setting1 entry will then show up in the settings grid.
In the Type drop-down of the new Setting1 entry, choose Connection String.
Click the ... button at the right end of the Setting1 entry. The Storage Account Connection String dialog will open.
Choose whether you want to target the storage emulator (Windows Azure storage simulated on your local machine) or a storage account in the cloud. The code in this guide works with either option.
NOTE:
You can target the storage emulator to avoid incurring any costs associated with Windows Azure Storage. However, if you do choose to target an Azure storage account in the cloud, costs for performing this tutorial will be negligible.
If you are targeting a storage account in the cloud, then enter the primary access key for that storage account. To learn how to copy your primary access key via the Azure Management Portal, see View, copy, and regenerate storage access keys.
Change the entry Name from Setting1 to a friendlier name like StorageConnectionString. You will reference this connection string later in the code in this guide.
Configuring your connection string using .NET configuration
If you are writing an application that is not an Azure cloud service, (see previous section), it is recommended you use the .NET configuration system (e.g. web.config
or app.config
). This includes Azure Websites or Azure Virtual Machines, as well as applications designed to run outside of Azure. You store the connection string using the <appSettings>
element as follows. Replace account-name
with the name of your storage account, and account-key
with your account access key:
<configuration>
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key" />
</appSettings>
</configuration>
For example, the configuration setting in your config file may be similar to:
<configuration>
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=nYV0gln9fT7bvY+rxu2iWAEyzPNITGkhM88J8HUoyofpK7C8fHcZc2kIZp6cKgYRUM74lHI84L50Iau1+9hPjB==" />
</appSettings>
</configuration>
You are now ready to perform the how-to tasks in this guide.
Programmatically access Blob storage
Obtaining the assembly
We recommend that you use NuGet to obtain the Microsoft.WindowsAzure.Storage.dll
assembly. Right-click your project in Solution Explorer and choose Manage NuGet Packages. Search online for "WindowsAzure.Storage" and click Install to install the Azure Storage package and dependencies.
Microsoft.WindowsAzure.Storage.dll
is also included in the Azure SDK for .NET, which can be downloaded from the .NET Developer Center. The assembly is installed to the %Program Files%\Microsoft SDKs\Azure\.NET SDK\<sdk-version>\ref\
directory.
Namespace declarations
Add the following namespace declarations to the top of any C# file in which you wish to programmatically access Azure Storage:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
Make sure you reference the Microsoft.WindowsAzure.Storage.dll
assembly.
Retrieving your connection string
You can use the CloudStorageAccount type to represent your Storage Account information. If you are using an Azure project template and/or have a reference to Microsoft.WindowsAzure.CloudConfigurationManager, you can you use the CloudConfigurationManager type to retrieve your storage connection string and storage account information from the Azure service configuration:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
If you are creating an application with no reference to Microsoft.WindowsAzure.CloudConfigurationManager, and your connection string is located in the web.config
or app.config
as show above, then you can use ConfigurationManager to retrieve the connection string. You will need to add a reference to System.Configuration.dll to your project, and add another namespace declaration for it:
using System.Configuration;
...
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
A CloudBlobClient type allows you to retrieve objects that represent containers and blobs stored within the Blob Storage Service. The following code creates a CloudBlobClient object using the storage account object we retrieved above:
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
ODataLib dependencies
ODataLib dependencies in the Storage Client Library for .NET are resolved through the ODataLib (version 5.0.2) packages available through NuGet and not WCF Data Services. The ODataLib libraries can be downloaded directly or referenced by your code project through NuGet. The specific ODataLib packages are OData, Edm, and Spatial.
Create a container
Every blob in Azure storage must reside in a container. This example shows how to create a container if it does not already exist:
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Create the container if it doesn't already exist.
container.CreateIfNotExists();
By default, the new container is private and you must specify your storage access key to download blobs from this container. If you want to make the files within the container available to everyone, you can set the container to be public using the following code:
container.SetPermissions(
new BlobContainerPermissions { PublicAccess =
BlobContainerPublicAccessType.Blob });
Anyone on the Internet can see blobs in a public container, but you can modify or delete them only if you have the appropriate access key.
Upload a blob into a container
Azure Blob Storage supports block blobs and page blobs. In the majority of cases, block blob is the recommended type to use.
To upload a file to a block blob, get a container reference and use it to get a block blob reference. Once you have a blob reference, you can upload any stream of data to it by calling the UploadFromStream method. This operation will create the blob if it didn't previously exist, or overwrite it if it does exist. The following example shows how to upload a blob into a container and assumes that the container was already created.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob"); // Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
{
blockBlob.UploadFromStream(fileStream);
}
List the blobs in a container
To list the blobs in a container, first get a container reference. You can then use the container's ListBlobs method to retrieve the blobs and/or directories within it. To access the rich set of properties and methods for a returned IListBlobItem, you must cast it to a CloudBlockBlob, CloudPageBlob, or CloudBlobDirectory object. If the type is unknown, you can use a type check to determine which to cast it to. The following code demonstrates how to retrieve and output the URI of each item in the photos
container:
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("photos"); // Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
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);
}
}
As shown above, the blob service has the concept of directories within containers, as well. This is so that you can organize your blobs in a more folder-like structure. For example, consider the following set of block blobs in a container named photos
:
photo1.jpg
2010/architecture/description.txt
2010/architecture/photo3.jpg
2010/architecture/photo4.jpg
2011/architecture/photo5.jpg
2011/architecture/photo6.jpg
2011/architecture/description.txt
2011/photo7.jpg
When you call ListBlobs on the 'photos' container (as in the above sample), the collection returned will contain CloudBlobDirectory and CloudBlockBlob objects representing the directories and blobs contained at the top level. Here would be the resulting output:
Directory: https://<accountname>.blob.core.windows.net/photos/2010/
Directory: https://<accountname>.blob.core.windows.net/photos/2011/
Block blob of length 505623: https://<accountname>.blob.core.windows.net/photos/photo1.jpg
Optionally, you can set the UseFlatBlobListing parameter of of the ListBlobs method to true. This would result in every blob being returned as a CloudBlockBlob , regardless of directory. Here would be the call to ListBlobs:
// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, true))
{
...
}
and here would be the results:
Block blob of length 4: https://<accountname>.blob.core.windows.net/photos/2010/architecture/description.txt
Block blob of length 314618: https://<accountname>.blob.core.windows.net/photos/2010/architecture/photo3.jpg
Block blob of length 522713: https://<accountname>.blob.core.windows.net/photos/2010/architecture/photo4.jpg
Block blob of length 4: https://<accountname>.blob.core.windows.net/photos/2011/architecture/description.txt
Block blob of length 419048: https://<accountname>.blob.core.windows.net/photos/2011/architecture/photo5.jpg
Block blob of length 506388: https://<accountname>.blob.core.windows.net/photos/2011/architecture/photo6.jpg
Block blob of length 399751: https://<accountname>.blob.core.windows.net/photos/2011/photo7.jpg
Block blob of length 505623: https://<accountname>.blob.core.windows.net/photos/photo1.jpg
For more information, see [CloudBlobContainer.ListBlobs][].
Download blobs
To download blobs, first retrieve a blob reference and then call the DownloadToStream method. The following example uses the DownloadToStream method to transfer the blob contents to a stream object that you can then persist to a local file.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Retrieve reference to a blob named "photo1.jpg".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("photo1.jpg"); // Save blob contents to a file.
using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
{
blockBlob.DownloadToStream(fileStream);
}
You can also use the DownloadToStream method to download the contents of a blob as a text string.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Retrieve reference to a blob named "myblob.txt"
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference("myblob.txt"); string text;
using (var memoryStream = new MemoryStream())
{
blockBlob2.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Delete blobs
To delete a blob, first get a blob reference and then call the Delete method on it.
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer"); // Retrieve reference to a blob named "myblob.txt".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob.txt"); // Delete the blob.
blockBlob.Delete();
List blobs in pages asynchronously
If you are listing a large number of blobs, or you want to control the number of results you return in one listing operation, you can list blobs in pages of results. This example shows how to return results in pages asynchronously, so that execution is not blocked while waiting to return a large set of results.
This example shows a flat blob listing, but you can also perform a hierarchical listing, by setting the useFlatBlobListing
parameter of the ListBlobsSegmentedAsync method to false
.
Because the sample method calls an asynchronous method, it must be prefaced with the async
keyword, and it must return a Task object. The await keyword specified for the ListBlobsSegmentedAsync method suspends execution of the sample method until the listing task completes.
async public static Task ListBlobsSegmentedInFlatListing()
{
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("myblobs"); //List blobs in pages.
Console.WriteLine("List blobs in pages:"); //List blobs with a paging size of 10, for the purposes of the example.
//The first call does not include the continuation token.
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(
"", true, BlobListingDetails.All, 10, null, null, null); //Enumerate the result segment returned.
int i = 0;
if (resultSegment.Results.Count<IListBlobItem>() > 0) { Console.WriteLine("Page {0}:", ++i); }
foreach (var blobItem in resultSegment.Results)
{
Console.WriteLine("\t{0}", blobItem.StorageUri.PrimaryUri);
}
Console.WriteLine(); //Get the continuation token, if there are additional pages of results.
BlobContinuationToken continuationToken = resultSegment.ContinuationToken; //Check whether there are more results and list them in pages of 10 while a continuation token is returned.
while (continuationToken != null)
{
//This overload allows control of the page size.
//You can return all remaining results by passing null for the maxResults parameter,
//or by calling a different overload.
resultSegment = await container.ListBlobsSegmentedAsync(
"", true, BlobListingDetails.All, 10, continuationToken, null, null);
if (resultSegment.Results.Count<IListBlobItem>() > 0) { Console.WriteLine("Page {0}:", ++i); }
foreach (var blobItem in resultSegment.Results)
{
Console.WriteLine("\t{0}", blobItem.StorageUri.PrimaryUri);
}
Console.WriteLine(); //Get the next continuation token.
continuationToken = resultSegment.ContinuationToken;
}
}
Next steps
Now that you've learned the basics of blob storage, follow these links to learn about more complex storage tasks.
- View the Blob service reference documentation for complete details about available APIs:
- Learn about more advanced tasks you can perform with Azure Storage at Storing and Accessing Data in Azure.
- Learn how to simplify the code you write to work with Azure Storage by using the Azure WebJobs SDK.
- View more feature guides to learn about additional options for storing data in Azure.
- Use Table Storage to store structured data.
- Use Queue Storage to store unstructured data.
- Use SQL Database to store relational data.
[转]windows azure How to use Blob storage from .NET的更多相关文章
- Windows Azure入门教学:使用Blob Storage
对于.net开发人员,这是一个新的领域,但是并不困难.本文将会介绍如何使用Blob Storage.Blob Storage可以看做是云端的文件系统.与桌面操作系统上不同,我们是通过REST API来 ...
- [New Portal]Windows Azure Virtual Machine (23) 使用Storage Space,提高Virtual Machine磁盘的IOPS
<Windows Azure Platform 系列文章目录> 注意:如果使用Azure Virtual Machine,虚拟机所在的存储账号建议使用Local Redundant.不建议 ...
- [Windows Azure] .NET Multi-Tier Application Using Storage Tables, Queues, and Blobs - 1 of 5
.NET Multi-Tier Application Using Storage Tables, Queues, and Blobs - 1 of 5 This tutorial series sh ...
- 跟我学Windows Azure 五 使用Cloub Service连接Blob Service完成图片的上传
首先,我们创建一个云服务项目,用来演示我们的blob存储 下来我们修改我们我们云服务的名字 我们需要添加一个空的WebForm的项目 点击完成,我们可以看到我们的解决方案已经添加完成 下来我们需要添加 ...
- Azure Functions(二)集成 Azure Blob Storage 存储文件
一,引言 上一篇文章有介绍到什么是 SeverLess ,ServerLess 都有哪些特点,以及多云环境下 ServerLess 都有哪些解决方案.在这众多解决方案中就包括 Function App ...
- Azure Blob Storage从入门到精通
今天推荐的是一个系列文章,让读者阅读完成后可以对Azure Blob Storage的开发有一个全面的了解,可谓是从入门到精通. Azure在最初的版本里面就提供了非结构化数据的存储服务,也即Blob ...
- Windows Azure Virtual Machine (26) 使用高级存储(SSD)和DS系列VM
<Windows Azure Platform 系列文章目录> Update: 2016-11-3,如果大家在使用Linux VM,使用FIO进行IOPS测试的时候,请使用以下命令: su ...
- Windows Azure 存储管理器 (2014)
Windows Azure存储用户经常希望能够在"管理器"中查看他们的数据,管理器指的是一款可用于显示存储帐户数据的工具.我们之前提供了我们所知的存储管理器列表.在本文中,我 ...
- [Windows Azure] Enabling Diagnostics in Windows Azure
Enabling Diagnostics in Windows Azure Windows Azure Diagnostics enables you to collect diagnostic da ...
随机推荐
- 关于disable和readonly
我们在做网页时,难免的会因为权限或者各种原因,想让使用者看到,但是却不想让用户去对值进行更改,我们有两个选择 一.我们使用disabled将文本框禁用掉. 二.我们使用readonly使得文本框只能读 ...
- C++标准I/O库:iostream, fstream, sstringstream
在写代码的过程中.我们最常做的事就是io操作,不管是对控制台,还是文件.但一段时间不写代码就忘了,这里理一下C++标准I/O库的详细类和操作. C++的标准I/O库包含我们常常使用的iostream, ...
- 解决centos yum安装"No package nginx available."问题
问题原因: nginx位于第三方的yum源里面,而不在centos官方yum源里面 解决方法: 安装epel(Extra Packages for Enterprise Linux) a.去epel网 ...
- Effective C++学习笔记(Part Two:Item 5-12)
近期最终把effectvie C++细致的阅读了一边,非常惊叹C++的威力与魅力.近期会把近期的读书心得与读书笔记记于此.必备查找使用,假设总结有什么不当之处,欢迎批评指正: 如今仅仅列出框架. ...
- 10 逻辑完善以及bug修复
进行到这里,我们应用开发已经接近尾声,我这里基本就是应用开发的记录过程,讲解的东西很少,有问题可以在评论区讨论呦.下面进入最后调整的阶段. 预览我们的应用,会发现首页的职位列表,也会显示收藏的星星图标 ...
- 返回模式有流式(streaming)和整体(total) 热词词表解决方案
重要术语说明_语音识别(ASR)_智能语音交互-阿里云 https://help.aliyun.com/document_detail/72238.html 返回模式(response mode) ...
- oracle经典建表语句--scott建表
create table EMP ( EMPNO ) PRIMARY KEY, ENAME ), JOB ), MGR ), HIREDATE DATE, SAL ,), COMM ,), DEPNO ...
- __setup 在内核中的作用【转】
本文转载自:http://blog.csdn.net/lanmanck/article/details/7613305 本文来自: http://blog.chinaunix.net/uid-1379 ...
- 删除oracle数据库用户的dba权限(当出现同一用户DBA可以登录,normal不能登录)“无法对SYS拥有的对象创建触发器”
系统报错:“无法对SYS拥有的对象创建触发器”,搞不懂是什么原因了,到底这触发器要用什么用户才能建立啊? ORA-04089: 无法对 SYS 拥有的对象创建触发器 第一种方式: 首先,用sys用户a ...
- 【Codevs1346】HelloWorld编译器
http://codevs.cn/problem/1346/ 可怜我战绩 // <1346.cpp> - 10/30/16 17:12:09 // This file is made by ...