title: Asynchronous download of an Azure blob to string with .NET 4.5 async, await
body: <p>I'm trying to implement a <strong>fully asynchronous</strong> blob download with .NET 4.5 async &amp; await.</p>
  
  <p>Let's assume the entire blob can fit in memory at once, and we want to hold it in a <code>string</code>.</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>public async Task&lt;string&gt; DownloadTextAsync(ICloudBlob blob)
  {
      using (Stream memoryStream = new MemoryStream())
      {
          IAsyncResult asyncResult = blob.BeginDownloadToStream(memoryStream, null, null);
          await Task.Factory.FromAsync(asyncResult, (r) =&gt; { blob.EndDownloadToStream(r); });
          memoryStream.Position = 0;
  
          using (StreamReader streamReader = new StreamReader(memoryStream))
          {
              // is this good enough?
              return streamReader.ReadToEnd();
  
              // or do we need this?
              return await streamReader.ReadToEndAsync();
          }
      }
  }
  </code></pre>
  
  <p><strong>Usage:</strong></p>
  
  <pre><code>CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));
  CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  CloudBlobContainer container = blobClient.GetContainerReference("container1");
  CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");
  
  string text = await DownloadTextAsync(blockBlob);
  </code></pre>
  
  <p>Is this code correct and this is indeed fully asynchronous? Would you implement this differently?</p>
  
  <p><strong>I'd appreciate some extra clarifications:</strong></p>
  
  <ol>
  <li><p><code>GetContainerReference</code> and <code>GetBlockBlobReference</code> don't need to be async since they don't contact the server yet, right?</p></li>
  <li><p>Does <code>streamReader.ReadToEnd</code> need to be async or not?</p></li>
  <li><p>I'm a little confused about what <code>BeginDownloadToStream</code> does.. by the time <code>EndDownloadToStream</code> is called, does my memory stream have <em>all</em> the data inside? or is the stream only open pre read?</p></li>
  </ol>
  
  <p><strong>Update: (as of Storage 2.1.0.0 RC)</strong></p>
  
  <p>Async now supported natively.</p>
  
  <pre><code>CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));
  CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
  CloudBlobContainer container = blobClient.GetContainerReference("container1");
  CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");
  
  string text = await blockBlob.DownloadTextAsync();
  </code></pre>