gpt4 book ai didi

c# - CloudBlob.DownloadToStream 返回 null

转载 作者:可可西里 更新时间:2023-11-01 08:19:45 25 4
gpt4 key购买 nike

我正在尝试通过流从 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();
}
}

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

enter image description here

这有什么问题吗?请帮忙。

编辑

不允许在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;
}

最佳答案

您的问题是您的输入流指针设置为 Steam 的末尾(参见屏幕截图,长度和位置都显示相同的值),这就是为什么当您读取它时您总是得到空值。您需要使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com