5

I'm rewriting my C# code to use Azure Blob storage instead of filesystem. So far no problems rewriting code for normal fileoperations. But I have some code that uses async write from a stream:

        using (var stream = await Request.Content.ReadAsStreamAsync())
        {
            FileStream fileStream = new FileStream(@"c:\test.txt", FileMode.Create, FileAccess.Write, FileShare.None);

            await stream.CopyToAsync(fileStream).ContinueWith(
             (copyTask) =>
             {
                 fileStream.Close();
             });
        }

I need to change the above to use Azure CloudBlockBlob or CloudBlobStream - but can't find a way to declare a stream object that copyToAsync can write to.

user8538243
  • 63
  • 1
  • 3
  • 1
    Possible duplicate of [Uploading to azure asynchronously directly from a stream](https://stackoverflow.com/questions/13891497/uploading-to-azure-asynchronously-directly-from-a-stream) – Bernard Vander Beken Nov 09 '17 at 09:53

1 Answers1

8

You would want to use UploadFromStreamAsync method on CloudBlockBlob. Here's a sample code to do so (I have not tried running this code though):

        var cred = new StorageCredentials(accountName, accountKey);
        var account = new CloudStorageAccount(cred, true);
        var blobClient = account.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference("container-name");
        var blob = container.GetBlockBlobReference("blob-name");
        using (var stream = await Request.Content.ReadAsStreamAsync())
        {
            stream.Position = 0;
            await blob.UploadFromStreamAsync(stream);
        }
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241