stream.CopyTo - file empty. asp.net

后端 未结 3 1822
旧巷少年郎
旧巷少年郎 2021-01-07 16:15

I\'m saving an uploaded image using this code:

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

When the im

相关标签:
3条回答
  • 2021-01-07 16:53

    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);
    }
    
    0 讨论(0)
  • 2021-01-07 17:09

    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()
    
    0 讨论(0)
  • 2021-01-07 17:10

    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.

    0 讨论(0)
提交回复
热议问题