stream.CopyTo - file empty. asp.net

拜拜、爱过 提交于 2019-11-30 21:31:20

问题


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.


回答1:


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.




回答2:


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;
    imageFile.CopyToAsync(fileStream);
}



回答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()


来源:https://stackoverflow.com/questions/9349571/stream-copyto-file-empty-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!