如何迭代容器中的 blob 列表并获取其内容?
根据您的描述,我建议您可以使用 CloudBlobContainer.ListBlobs 方法列出容器中的 blob。然后,您可以使用 CloudBlockBlob.DownloadToStream 方法将 blob 下载到函数的内存流中,以获取存储 blob 文件的内容。
更多详细信息,您可以参考下面的代码。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
"connectionstring");
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("contiainername");
// Loop over items within the container and output the content, length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
string text;
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream);
//we get the content from the blob
//sine in my blob this is txt file,
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
Console.WriteLine(text);
}
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;
Getblobcontent(directory);
Console.WriteLine("Directory: {0}", directory.Uri);
}
}
获取azure存储blob目录中的blob内容:
private static void Getblobcontent(CloudBlobDirectory container)
{
foreach (IListBlobItem item in container.ListBlobs())
{
if (item.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob)item;
//int this method you could get the blob content in the directory
string text;
using (var memoryStream = new MemoryStream())
{
blob.DownloadToStream(memoryStream);
//we get the content from the blob
//sine in my blob this is txt file,
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
Console.WriteLine(text);
Console.WriteLine("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri);
}
else if (item.GetType() == typeof(CloudPageBlob))
{
CloudPageBlob pageBlob = (CloudPageBlob)item;
//int this method you could get the blob content
Console.WriteLine("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri);
}
else if (item.GetType() == typeof(CloudBlobDirectory))
{
CloudBlobDirectory directory = (CloudBlobDirectory)item;
Getblobcontent(directory);
Console.WriteLine("Directory: {0}", directory.Uri);
}
}
}