Convert MemoryStream to FileStream with C#?
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.
morcillo
Updated on June 28, 2022Comments
-
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. about 12 yearsThe
using
statement would like to have a chat with you :) -
Beenish Khan about 12 yearsEd, 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 about 12 yearsThis converts FileStream to MemoryStream, however question was how to convert MemoryStream to FileStream.
-
Feidex about 12 yearsThe 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. 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()
orSetLength()
throws you don't clean up your stream. This is not equivalent to using ausing
statement, it contains a bug). -
Beenish Khan about 12 years@Ed, to each his own. I like to point in the direction :)
-
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 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 :)