问题描述
通过.NET Azure Storage Blobs SDK , 获取Blob的MD5值,查看了Azure操作手册中,介绍可以使用 blob.Properties.ContentMD5 属性。
//blob 文件测试
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("file");
CloudBlockBlob blob = container.GetBlockBlobReference(@"image-03.jpg");
blob.UploadFromFile(filePath1, FileMode.OpenOrCreate);
Console.WriteLine("md5=" + blob.Properties.ContentMD5);
但是,在项目中,发现SDK更新后(Azure.Storage.Blobs 12.9.1)后,Properties中并没有ContentMD5属性?
问题解答
查看Blob Properties属性的源代码,发现没有了ContentMD5, 但是可以使用ContentHash。如果把ContentHash进行Base64编码后,它的结果就和Azure门户中的Content-MD5值一样:
示例代码如下:
static async Task GetBlobMD5Async(string connectionString,string containerName)
{
//// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
Console.WriteLine("Listing blobs...");
// List all blobs in the container
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
BlobClient bclient = containerClient.GetBlobClient(blobItem.Name);
// Get the blob properties
BlobProperties properties = await bclient.GetPropertiesAsync();
// Display some of the blob's property values
Console.WriteLine($"\t\t ContentLanguage: {properties.ContentLanguage}");
Console.WriteLine($"\t\t ContentType: {properties.ContentType}");
Console.WriteLine($"\t\t CreatedOn: {properties.CreatedOn}");
Console.WriteLine($"\t\t LastModified: {properties.LastModified}");
Console.WriteLine($"\t\t ContentHash: {FormatHashValue(properties.ContentHash)}");
Console.WriteLine($"\t\t ContentMD5: {Convert.ToBase64String(properties.ContentHash)}");
}
}
public static string FormatHashValue(byte[] contentHash)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < contentHash.Length; i++)
{
sb.Append(contentHash[i].ToString("x2"));
}
return sb.ToString();
}
参考资料
如何调用 API 获取 Azure File 存储中文件的 MD5值:https://docs.azure.cn/zh-cn/articles/azure-operations-guide/storage/aog-storage-blob-file-md5
BlobProperties.ContentHash Property: https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.models.blobproperties.contenthash?view=azure-dotnet
Manage blob properties and metadata with .NET : https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-properties-metadata#set-and-retrieve-properties
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
标签:ContentHash,Console,Storage,blob,WriteLine,Azure,properties,Blob From: https://blog.51cto.com/u_13773780/8354553