【发布时间】:2011-08-02 12:02:38
【问题描述】:
使用 Windows Azure 存储客户端库,CloudBlob.OpenRead() 方法仅读取 4 mb 的数据。如何使用 OpenRead 方法读取完整流。
CloudBlob blob = container.GetBlobReference(filename);
Stream stream = blob.OpenRead();
我必须使用 OpenRead 方法。无法使用 DownloadToFile 或 DownloadToStream。
编辑: 我范围之外的消费者代码调用
stream.CopyTo(readIntoStream);
CopyTo 是一种扩展方法。
public static int CopyTo(this Stream source, Stream destination)
{
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
int bytesCopied = 0;
do
{
bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
if (bytesRead > 0)
destination.Write(buffer, 0, bytesRead);
bytesCopied += bytesRead;
}
while (bytesRead > 0);
return bytesCopied;
}
编辑 2:
我观察到,当使用 blob.UploadText() 方法上传文件时,它可以正常工作,但是当按照以下代码示例使用 OpenWrite 方法上传 blob 时,OpenRead 方法仅读取 4194304 字节 (4 mb)。
using(var input = File.OpenRead(@"C:\testFile.txt")) //5000000 bytes
using (var output = blob.OpenWrite())
{
input.CopyTo(output);
}
编辑 3:
在我的最后产生问题的完整代码。
static void Main(string[] args)
{
var blobContainer = GetContainer("tier1");
blobContainer.CreateIfNotExist();
var containerPermissions = new BlobContainerPermissions();
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
blobContainer.SetPermissions(containerPermissions);
var blob = blobContainer.GetBlobReference("testfileWithOpenWrite1.txt");
using (var input = File.OpenRead(@"C:\testFile.txt")) //5000000 bytes
using (var output = blob.OpenWrite(new BlobRequestOptions()))
input.CopyTo(output);
Console.WriteLine("uploaded");
int bytesDownloaded = 0;
byte[] buffer = new byte[65536];
using (BlobStream bs = blob.OpenRead())
{
int chunkLength;
do
{
chunkLength = bs.Read(buffer, 0, buffer.Length);
bytesDownloaded += chunkLength;
} while (chunkLength > 0);
}
Console.WriteLine(bytesDownloaded);
}
public static int CopyTo(this Stream source, Stream destination)
{
int BUFFER_SIZE = 65536;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
int bytesCopied = 0;
do
{
bytesRead = source.Read(buffer, 0, BUFFER_SIZE);
if (bytesRead > 0)
destination.Write(buffer, 0, bytesRead);
bytesCopied += bytesRead;
}
while (bytesRead > 0);
return bytesCopied;
}
编辑 4 - 结论:
这可能是 SDK v1.2 附带的 Microsoft.WindowsAzure.StorageClient.dll(程序集版本 6.0.6002.17043)中的一个错误。它适用于最新的 Microsoft.WindowsAzure.StorageClient.dll(程序集版本 6.0.6002.18312 - SDK v1.4)。
谢谢 smarx :)
【问题讨论】:
-
请在调用
OpenRead后添加显示您对stream执行操作的代码。 -
您确定 blob 存储中的文件大于 4MB?