10

我有以下代码:

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 的测试和测试。

有任何想法吗?

4

1 回答 1

15

啊,我想通了……

以下几行:

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

需要改为

long streamlen = stream.Length;  
stream.Position = 0;
blockBlob.UploadFromStream(stream);   
于 2013-08-07T22:08:05.917 回答