以编程方式访问Blob存储
获取组件
您可以使用NuGet来获取Microsoft.WindowsAzure.Storage.dll
组件。 在Solution Explorer里右键点击你的Project, 然后选择Manage Nuget Packages, 在线搜索 “WindowsAzure.Storage” 然后点击安装Azure存储包和相关包。
Azure SDK .NET版也包含Microsoft.WindowsAzure.Storage.dll
, 您可以在.NET k开发者中心拿到。 该组件安装在%Program Files%\Microsoft SDKs\Azure\.NET SDK\<sdk-version>\ref\
目录下。
名字空间声明
把下面的代码加到你的C#程序的最上面以便于您访问Azure存储:
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
确保您引用Microsoft.WindowsAzure.Storage.dll
组件
检索连接字符串
您可以使用CloudStorageAccount 类型来展示您的存储账户信息。 如果您使用Azure项目模板或者您有一个关于Microsoft.WindowsAzure.CloudConfigurationManager名字空间的引用, 您也可以是用CloudConfigurationManager 类型从Azure服务配置表来检索您的存储连接字符串和账户信息。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
如果您的应用没有引用Microsoft.WindowsAzure.CloudConfigurationManager, 并且您的连接字符串存放在web.config或者app.config里, 那您就可以使用ConfigurationManager来获取连接字符串了。 不过您还需要添加一个对于System.Configuration.dll 的引用, 然后再添加一个命名空间的声明。
using System.Configuration;
using System.Configuration;
...
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
ConfigurationManager.ConnectionStrings["StorageConnectionString"]);
CloudBlobClient 类型允许检索能存储在Blob存储服务中的容器或者blobs对象。 下面的代码通过我们检索到的存储账户对象创建了一个CloudBlobClient 对象
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
创建一个容器
Azure存储里的每一个blob都必须包含在一个容器里。 blob名称是容器窗体的一部分。 例如, mycontainer
是下面blob URL中的一个容器:
https://storagesample.blob.core.windows.net/mycontainer/blob1.txt
https://storagesample.blob.core.windows.net/mycontainer/photos/myphoto.jpg
需要注意的是:
容器的名字必须是小写的。 如果您包含大写, 可能会受到404错误
下面例子介绍如何新添加一个容器:
// 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();
默认的情况下, 新添加的容器是私有的, 你必须指定您的账户key才能从这个容器里下载blob。 如果您想对每个人开放, 也可以设置成公开的。代码如下:
container.SetPermissions(
new BlobContainerPermissions { PublicAccess =
BlobContainerPublicAccessType.Blob });
网络上的任何人都可以看到公开容器中的blobs, 但是只有拥有access key的人才能修改或者删除。
上传blob到容器中
Azure blob存储支持块blob和页blob。 在大多数情况下, 推荐使用块blob。
您需要一个容器引用来获取blob引用才能向blob上传一个文件。 当您有了blob引用之后, 您可以使用UploadFromStream 方法来上传任意类型的数据流。 这个过程中如果您还没有blob, 系统会自动新建一个blob。 如果已经有了, 则会自动覆盖。下面的例子就是用来演示如何上传一个blob到容器中。
// 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);
}
列举容器中的blobs
如果想要列举容器中的blob, 您首先需要有一个容器引用。 然后您可以容器的ListBlobs 方法来检索容器内的blobs或者文件夹。如果您要是想访问返回的IListBlobItem的所有properties或者方法, 您必须把类型转化为CloudBlockBlob, CloudPageBlob或者CloudBlobDirectory 对象。 如果类型未知, 则您使用类型判断来确认然后转化。 下面是实例代码:
// 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);
}
}
下载Blobs
想要下载blobs, 首先需要检索blob引用, 然后调用DownloadToStream 方法。 下面的例子使用DownloadToStream方法来传输blob内容到流对象, 然后再存储到本地文件。
// 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);
}
您也可以使用DownloadToStream方法来下载整个blob的内容为一个文本串。
// 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());
}
删除blob
删除blob需要首先拿到一个blob引用然后调用Delete方法
// 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();
分页异步显示blob
如果您有很多的blob要显示, 或者您想显示特定数量的blob, 您可以使用不同的页来显示。 示例代码如下:
async public static Task ListBlobsSegmentedInFlatListing(CloudBlobContainer container)
{
//List blobs to the console window, with paging.
Console.WriteLine("List blobs in pages:");
int i = 0;
BlobContinuationToken continuationToken = null;
BlobResultSegment resultSegment = null;
//Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
//When the continuation token is null, the last page has been returned and execution can exit the loop.
do
{
//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 continuation token.
continuationToken = resultSegment.ContinuationToken;
}
while (continuationToken != null);
}