如何使用 C# 中的 Azure.Storage.Blobs 从 Azure 存储 blob 获取 ByteArray 格式的文件

Sac*_*hin 15 .net c# azure azure-storage azure-blob-storage

我需要使用新包 Azure.Storage.Blobs 从 Azure 存储中获取字节数组格式的文件。我无法找到在 C# 中执行此操作的方法。

public byte[] GetFileFromAzure()
{
byte[] filebytes; 
    BlobServiceClient blobServiceClient = new BlobServiceClient( "TestClient");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("TestContainer");
BlobClient blobClient = containerClient.GetBlobClient("te.xlsx");
    if (blobClient.ExistsAsync().Result)
{
    var response = blobClient.DownloadAsync().Result;
    using (var streamReader = new StreamReader(response.Value.Content))
    {
        var line = streamReader.ReadToEnd();
        //No idea how to convert this to ByteArray
    }
}
return filebytes;
}
Run Code Online (Sandbox Code Playgroud)

知道如何实现获取存储在 Azure Blob 存储上的文件字节数组吗?

感谢帮助。

Dav*_*sey 34

尝试以下操作将 Blob 作为流读取,然后在返回时将该流转换为字节数组:

public byte[] GetFileFromAzure()
{
    BlobServiceClient blobServiceClient = new BlobServiceClient( "TestClient");
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("TestContainer");
    BlobClient blobClient = containerClient.GetBlobClient("te.xlsx");
    
    if (blobClient.ExistsAsync().Result)
    {
        using (var ms = new MemoryStream())
        {
            blobClient.DownloadTo(ms);
            return ms.ToArray();
        }
    }   
    return new byte[];  // returns empty array
}
Run Code Online (Sandbox Code Playgroud)