2013-08-07 21 views
6

Mam następujący kod:Dlaczego CloudBlockBlob.DownloadToStream zawsze zwraca pusty strumień?

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);   
} 

i

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; 
} 

biegnę to w emulatorze Azure, które wskazują na moim SQL Server.

Z tego co wiem, wygląda na to, że UploadFromStream prawidłowo wysyła dane, jednak jeśli spróbuję uruchomić DownloadStreamFromBlob, zwraca strumień o długości 0. Argument blockBlob.Exists zwraca true, więc zakładam, że jest. Po prostu nie mogę zrozumieć, dlaczego mój strumień jest pusty.

Przy okazji przechodzę test i test dla nazwy kontenera i elementu blobName dla obu połączeń.

Wszelkie pomysły?

Odpowiedz

10

Ach, zdobione ...

następujące wiersze:

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

muszą zostać zmienione, aby

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

+1: tylko pomógł mi z pustym Blob pobierz scenariusz ... Tak często to proste szczegóły, które nas wyzwalają. –

+1

Jest to częsty problem podczas pracy ze strumieniami. I allays ustawione na moje metody IO 'stream.Seek (0, SeekOrigin.Begin);' –