我正在尝试通过流从cloudBlob下载文件。我引用这篇文章CloudBlob

这是下载Blob的代码

public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri)
{
    Stream mem = new MemoryStream();
    CloudBlobClient blobclient = account.CreateCloudBlobClient();
    CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri);

    if (blob != null)
        blob.DownloadToStream(mem);

    return mem;
}

和将其转换为字节数组的代码
    public static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

但是我总是得到空值。以下是流文件的内容。



这有什么问题?请帮忙。

编辑

不允许在ReadFully方法中将Position设置为0,因此我将其放在DownloadBlobAsStream

现在应该可以使用:
public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri)
{
    Stream mem = new MemoryStream();
    CloudBlobClient blobclient = account.CreateCloudBlobClient();
    CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri);

    if (blob != null)
        blob.DownloadToStream(mem);
    mem.Position = 0;
    return mem;
}

最佳答案

您的问题是您的输入流指针设置为流的结尾(请参见屏幕快照,“长度”和“位置”都显示相同的值),这就是为什么在读取时始终获得null的原因。您需要使用 Stream.Position = 0 来设置输入流指针为0,如下所示:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16 * 1024];

    input.Position = 0; // Add this line to set the input stream position to 0

    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

关于c# - CloudBlob.DownloadToStream返回null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10891857/

10-11 02:59