CloudBlob.DownloadToStream返回null [英] CloudBlob.DownloadToStream returns null

查看:342
本文介绍了CloudBlob.DownloadToStream返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过流从cloudBlob下载一个文件。我参考这篇文章 CloudBlob

I'm trying to download a file from cloudBlob via stream. I refer to this article CloudBlob

以下是下载blob的代码

Here is the code to download the 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;
}  

并将代码转换为字节数组

And the code to convert it into byte array

    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();
        }
    }  

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

But I always get null value. Below is the content of the streamed file.

这有什么问题?请帮助。

What is wrong with this? Please help.

编辑

将位置设置为0 < $ c> ReadFully 方法不允许,所以我把它放在 DownloadBlobAsStream

Setting the Position to 0 inside ReadFully method is not allowed, so I put it inside 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,如下所示:

Your problem is that your input stream pointer is set to end of the steam (See the screen shot, Length and Position both shows same value) that's why when you read it you always get null. You would need to set to input stream pointer to 0 using Stream.Position = 0 as below:

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();
    }
} 

这篇关于CloudBlob.DownloadToStream返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆