[ACCEPTED]-stream.CopyTo - file empty. asp.net-filestream

Accepted answer
Score: 83

There is nothing wrong with your code. The 12 fact you say "I've checked the stream.Length 11 before copying and its not empty" makes 10 me wonder about the stream position before copying.

If you've 9 already consumed the source stream once 8 then although the stream isn't zero length, its 7 position may be at the end of the stream 6 - so there is nothing left to copy.

If the 5 stream is seekable (which it will be for 4 a MemoryStream or a FileStream and many others), try putting

stream.Position = 0

just 3 before the copy. This resets the stream 2 position to the beginning, meaning the whole 1 stream will be copied by your code.

Score: 3

I would recommend to put the following before 2 CopyTo()

fileStream.Position = 0

Make sure to use the Flush() after this, to avoid 1 empty file after copy.

Score: 1

This problem started for me after migrating 3 my project from to .NET Core 1 to 2.2.

I 2 fixed this issue by setting the Position of my filestream 1 to zero.

using (var fileStream = new FileStream(savePath, FileMode.Create))
    fileStream.Position = 0;
    await imageFile.CopyToAsync(fileStream);

More Related questions