如何使用.net在Azure中获取Blob的内容?



我在Azure中从blob检索数据时遇到了一个问题。我的代码如下:

static async Task Main()
{   
BlobServiceClient blobServiceClient = new BlobServiceClient("*");
BlobContainerClient containerClient =  blobServiceClient.GetBlobContainerClient("*");

var blobClient = containerClient.GetBlobClient("*");
var content = blobClient.DownloadContent();
BinaryData data = new BinaryData(content);
var blobContents = Encoding.UTF8.GetString(data);
Console.WriteLine("t" + data);
}

但是结果显示了除了内容区域之外的所有属性:

{"Value":{"Details":{"BlobType":0,"ContentLength":66924,"ContentType":"application/octet-stream","ContentHash":"JwTlI7cLcG+FWuewCaRuaQ==","LastModified":"2021-04-10T00:18:36+00:00","Metadata":{},"ContentRange":null,"ETag":"u00220x8D8FBB62F1EC10Cu0022","ContentEncoding":null,"CacheControl":null,"ContentDisposition":null,"ContentLanguage":null,"BlobSequenceNumber":0,"CopyCompletedOn":"0001-01-01T00:00:00+00:00","CopyStatusDescription":null,"CopyId":null,"CopyProgress":null,"CopySource":null,"CopyStatus":0,"LeaseDuration":0,"LeaseState":0,"LeaseStatus":1,"AcceptRanges":"bytes","BlobCommittedBlockCount":0,"IsServerEncrypted":true,"EncryptionKeySha256":null,"EncryptionScope":null,"BlobContentHash":null,"TagCount":0,"VersionId":null,"IsSealed":false,"ObjectReplicationSourceProperties":null,"ObjectReplicationDestinationPolicyId":null,"LastAccessed":"0001-01-01T00:00:00+00:00","ImmutabilityPolicy":{"ExpiresOn":null,"PolicyMode":null},"HasLegalHold":false},"Content":{}}}

所以我将代码修改如下:

class Program
{
static async Task Main()
{   
BlobServiceClient blobServiceClient = new BlobServiceClient("*");
BlobContainerClient containerClient =  blobServiceClient.GetBlobContainerClient("*");
var blobClient = containerClient.GetBlobClient("*");  
string localPath = "./data/tmp.datablock";
blobClient.DownloadTo(localPath);

string contents;
using (StreamReader streamReader = new StreamReader("./data/tmp.datablock", Encoding.UTF8))
{
contents = streamReader.ReadToEnd();
}
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = System.Text.Json.JsonSerializer.Serialize(contents, options);
Dictionary<string, dynamic>? values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(contents);

foreach(var pair in values)
{
Console.WriteLine(pair.Value);
}  
}
}

它成功了。

我只是不知道为什么我的第一种方法不起作用。还有更好的方法来获取blob的内容吗?

谢谢大家!

BlobClient.Download方法的结果为BlobDownloadResult类型的响应。要读取blob的内容,您需要使用那里的Content属性。

请尝试以下代码:

static async Task Main()
{   
BlobServiceClient blobServiceClient = new BlobServiceClient("*");
BlobContainerClient containerClient =  blobServiceClient.GetBlobContainerClient("*");
var blobClient = containerClient.GetBlobClient("*");
var response = blobClient.DownloadContent();
BinaryData data = response.Value.Content;
var blobContents = Encoding.UTF8.GetString(data);
Console.WriteLine("t" + data);
}

相关内容

  • 没有找到相关文章

最新更新