Saving a stream to file

  • Thread starter Thread starter jester
  • Start date Start date
J

jester

Hi! I have a very simple problem. I'm calling a method w/c
returns a Stream. How do I save the stream to file?
Currently what I do is (in pseudo-code):

returnedStream.Read(arrayOfBytes)
FileStream outFile = File.Create(...)
outFile.Write(arrayOfBytes)
//-Flush, close, cleanup, etc...

I don't think this is the best way of doing it. Any help
is greatly appreciated. Thanks :)
 
jester said:
Hi! I have a very simple problem. I'm calling a method w/c
returns a Stream. How do I save the stream to file?
Currently what I do is (in pseudo-code):

returnedStream.Read(arrayOfBytes)
FileStream outFile = File.Create(...)
outFile.Write(arrayOfBytes)
//-Flush, close, cleanup, etc...

I don't think this is the best way of doing it. Any help
is greatly appreciated. Thanks :)

Rather than calling Read and ignoring the return value, read into a
buffer, writing however much you've read, and then keeping going until
the stream you're reading has finished.

See http://www.pobox.com/~skeet/csharp/readbinary.html for some sample
code - it's not aimed exactly at your problem, but should give you a
good idea of what to do.
 
So I suppose there's no direct method of saving a stream
to file? I really have to do Stream-->ArrayOfBytes--
ReadArrayOfBytesIntoAnotherStream--
WriteAnotherStreamToFile.

No way I can directly do Stream-->WriteStreamToFile?
Thanks.
 
jester said:
So I suppose there's no direct method of saving a stream
to file? I really have to do Stream-->ArrayOfBytes--

You don't have to read the whole thing into a single array at a time -
you can just have a buffer, and never have more than that buffer in
memory at any one time.
No way I can directly do Stream-->WriteStreamToFile?

Well, it would be very easy to write such a method, but there isn't one
in the framework itself.
 
Back
Top