Convert MemoryStream to FileStream with C#?

10,652

If I understand your question correctly, you have a method that returns a MemoryStream, and you need to pass that stream to a method that takes a FileStream. I've seen several instances where colleagues of mine have written methods with a FileStream parameter when the parameter type could have been Stream. This is an excellent example of why it's better to use the less-derived type for the parameter.

The only solution I can think of is to write the memory stream to a temporary file: create a file stream for the temporary file, copy the memory stream to the file stream, and then either set the position to zero or close the stream and open a new stream on the same file, to pass to the method.

If I have misunderstood your question, please clarify.

Share:
10,652
morcillo
Author by

morcillo

Updated on June 28, 2022

Comments

  • morcillo
    morcillo almost 2 years

    I am working on a project that receives a FileStream and it should receive it with a method that returns a MemoryStream.

    How can I convert the MemoryStream to FileStream? I can't touch those codes and there lies the entire problem.

  • Ed S.
    Ed S. about 12 years
    The using statement would like to have a chat with you :)
  • Beenish Khan
    Beenish Khan about 12 years
    Ed, this is to give an idea of how to do it, I trust them to take it on from here and close/flush in the best possible manner :)
  • Ňuf
    Ňuf about 12 years
    This converts FileStream to MemoryStream, however question was how to convert MemoryStream to FileStream.
  • Feidex
    Feidex about 12 years
    The Read method does not necessarily read count -many bytes into the buffer. It needs to be called repeatedly until the buffer is filled.
  • Ed S.
    Ed S. about 12 years
    @BeenishKhan: Me thinks you are too trusting. It actually requires fewer characters to do the right thing, so I don't understand doing it the wrong way purposely (and yes, it is wrong because if Read() or SetLength() throws you don't clean up your stream. This is not equivalent to using a using statement, it contains a bug).
  • Beenish Khan
    Beenish Khan about 12 years
    @Ed, to each his own. I like to point in the direction :)
  • Ed S.
    Ed S. about 12 years
    @BeenishKhan: Problem being you pointed in the wrong direction. There is a difference between handing something a complete code sample ready for use in production code and using best practices / elminating obvious bugs.
  • Beenish Khan
    Beenish Khan about 12 years
    @Ed, You can always make edit to answers if you believe there is a problem :) As XtremeProgramming says, just go ahead and fix it :)