2

I'm trying to download a blob file as a bytearray from my blob account on Azure. I do this.

 var blockBlob = blobContainer.GetBlockBlobReference(id);

                using (var mStream = new MemoryStream())
                {
                    blockBlob.DownloadToStreamAsync(mStream);
                    result = mStream.ToArray();
                }

The code above returns me a empty stream. I do have the file on my azure blob account and I checked the uri that is generated by code and it's the same that the one on my azure blob for the file I want to download as bytearray.

Is there a better way to download a azure blob file as bytearray in c#?

Victor A Chavez
  • 181
  • 1
  • 19
  • 4
    Also, wait for the async operation to finish. Try adding await before the DownloadToStreamAsync method call. Something like “await blockBlob.DownloadToStreamAsync(ms)”. – Gaurav Mantri Apr 20 '18 at 01:50

2 Answers2

3

You should wait till the async operation gets completed.

          using (var mStream = new MemoryStream())
            {

                 await  blockBlob.DownloadToStreamAsync(mStream);
                 result = mStream.ToArray();
            }

You are getting empty because you try to get value from it when it is not yet available.

  • While this is 'Correct'. It could probably do with some clarification of what async and await does and how you use the keyword, as it appears OP might not have much knowledge of async and await – Dave Apr 22 '18 at 17:42
  • I get empty files w/ this answer. Result should have at least var in front of it, no? – greg Nov 27 '19 at 13:22
  • 1
    https://stackoverflow.com/questions/52728786/cannot-download-azure-blob-to-stream see also this - you may need to set position of the stream – Jay May 05 '22 at 14:52
1

Two options for you to refer

  • As @Gaurav has said, use await blockBlob.DownloadToStreamAsync(mStream)
    Note that your method should change to public async Task methodname() if use this await.
  • Just use blockBlob.DownloadToStream(mStream) if async method is not necessary for you.

Some references for you

Jerry Liu
  • 17,282
  • 4
  • 40
  • 61