Copy MemoryStream to FileStream and save the file?

后端 未结 3 1492
抹茶落季
抹茶落季 2020-12-03 04:24

I don\'t understand what I\'m doing wrong here. I generate couple of memory streams and in debug-mode I see that they are populated. But when I try to copy MemoryStrea

相关标签:
3条回答
  • 2020-12-03 04: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.

    0 讨论(0)
  • 2020-12-03 04:53

    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.

    0 讨论(0)
  • 2020-12-03 04:58

    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:

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

    No need to set the stream position first either, since the .ToArray() operation explicitly ignores that, as per @BaconBits comment below https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream.toarray?view=netframework-4.7.2.

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