33

I am trying to upload the file that I have stored in MemoryStream using the following code.

        private static void SaveStream(MemoryStream stream, string fileName)
        {
            var blobStorageService = new BlobStorageService();
            UploadBlob(stream, fileName);
        }

        public void UploadBlob(MemoryStream fileStream,string fileName)
        {
            var blobContainer = _blobServiceClient.GetBlobContainerClient(Environment
                               .GetEnvironmentVariable("ContainerName"));
            var blobClient = blobContainer.GetBlobClient(fileName);
            blobClient.Upload(fileStream);  <--- Error Message

        }

Error Message: System.ArgumentException: 'content.Position must be less than content.Length.Please set content.Position to the start of the data to upload.'

1 Answer 1

77

This happened because the current position is at the end of the stream. You can set the position to the start of the stream before uploading

var blobClient = blobContainer.GetBlobClient(fileName);
fileStream.Position =0;
blobClient.Upload(fileStream)
Sign up to request clarification or add additional context in comments.

4 Comments

It might be worth explaining what is wrong with OP's code (i.e. why they are getting that message). :)
I wouldn't mind a refresher on that myself.
Explaining in layman's term : Stream is a one way data structure, when you read stream character by character, it's position starts moving forward. So if you have a code that has read the entire fileStream then it's position will be moved to the end. When you try to perform upload of fileStream - it's already read till the last character, so the uploader will throw an exception saying that there's nothing further to read. In order to solve this - we manually set the fileStream's position to the 0th position, hence the fileStream is again fresh to be read. And that's why the upload works!
TL;DR be kind, rewind

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.