Copy MemoryStream to FileStream and save the file?

折月煮酒 提交于 2019-11-27 08:12:51

You need to reset the position of the stream before copying.

outStream.Position = 0;
outStream.CopyTo(fileStream);

You used the outStream when saving the file using the imageFactory. That function populated the outStream. While populating the outStream the position is set to the end of the populated area. That is so that when you keep on writing bytes to the steam, it doesn't override existing bytes. But then to read it (for copy purposes) you need to set the position to the start so you can start reading at the start.

If your objective is simply to dump the memory stream to a physical file (e.g. to look at the contents) - it can be done in one move:

memoryStream.Position = 0;
System.IO.File.WriteAllBytes(@"C:\\filename", memoryStream.ToArray());

Another alternative to CopyTo is WriteTo.

Advantage:

No need to reset Position.

Usage:

outStream.WriteTo(fileStream);                

Function Description:

Writes the entire contents of this memory stream to another stream.

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