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

Sco*_*tie 8 streaming azure 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);        
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

顺便说一句,我在两个调用中传递了对containerName和blobName的测试和测试.

有任何想法吗?

Sco*_*tie 14

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

以下行:

long streamlen = stream.Length;
blockBlob.UploadFromStream(stream);   
Run Code Online (Sandbox Code Playgroud)

需要改为

long streamlen = stream.Length;  
stream.Position = 0;
blockBlob.UploadFromStream(stream);   
Run Code Online (Sandbox Code Playgroud)

  • +1:刚刚帮助我摆脱了一个空的Blob下载场景......所以经常是让我们感到高兴的简单细节. (2认同)