为什么CloudBlockBlob.DownloadToStream总是返回一个空流?

时间:2013-08-07 21:50:01

标签: azure streaming azure-storage-blobs

我有以下代码:

public static void UploadStreamToBlob(Stream stream, string containerName, string blobName)
{
    CloudStorageAccount storageAccount = 
        CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
    blobContainer.CreateIfNotExists();
    blobContainer.SetPermissions(
        new BlobContainerPermissions
        {
            PublicAccess = BlobContainerPublicAccessType.Blob
        });

    CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);
    long streamlen = stream.Length;  <-- This shows 203 bytes
    blockBlob.UploadFromStream(stream);        
}

public static Stream DownloadStreamFromBlob(string containerName, string blobName)
{
    CloudStorageAccount storageAccount = 
        CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);

    Stream stream = new MemoryStream();
    CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(blobName);

    if (blockBlob.Exists())
    {
        blockBlob.DownloadToStream(stream);
        long streamlen = stream.Length;  <-- This shows 0 bytes
        stream.Position = 0;          
    }

    return stream;
}

我在Azure模拟器中运行它,我已经指向我的Sql Server。

据我所知,似乎UploadFromStream正在正确发送数据,但是,如果我尝试运行DownloadStreamFromBlob,它将返回0长度的流。 blockBlob.Exists返回true,所以我认为它就在那里。我只是想不通为什么我的流是空的。

顺便说一句,我在两次调用中都传递了containerName和blobName的测试和测试。

有什么想法吗?

1 个答案:

答案 0 :(得分:12)

啊,我想通了......

以下几行:

long streamlen = stream.Length;
blockBlob.UploadFromStream(stream);   

需要更改为

long streamlen = stream.Length;  
stream.Position = 0;
blockBlob.UploadFromStream(stream);