33

I'm saving an uploaded image using this code:

using (var fileStream = File.Create(savePath))
{
   stream.CopyTo(fileStream);
}

When the image is saved to its destination folder, it's empty, 0 kb. What could possible be wrong here? I've checked the stream.Length before copying and its not empty.

Chris Catignani
  • 3,857
  • 6
  • 29
  • 40
user1121487
  • 2,464
  • 8
  • 36
  • 61
  • 3
    Can we see your code where you load the original stream please? Also, try inserting the line stream.Seek(0, SeekOrigin.Begin); just before your copy to to make sure you are at the beginning of the original stream. – dash Feb 19 '12 at 13:35

3 Answers3

77

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

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

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

stream.Position = 0

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

Rob Levine
  • 37,567
  • 13
  • 78
  • 108
3

I would recommend to put the following before CopyTo()

fileStream.Position = 0

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

fileStream.Flush()
Rohit416
  • 3,114
  • 3
  • 21
  • 38
chris
  • 31
  • 1
1

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

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

using (var fileStream = new FileStream(savePath, FileMode.Create))
{
    fileStream.Position = 0;
    await imageFile.CopyToAsync(fileStream);
}
Community
  • 1
  • 1
TidyDev
  • 2,827
  • 8
  • 23
  • 39