Groups | Blog | Home
all groups > dotnet faqs > october 2004 >

dotnet faqs : Stream Writer


Charles A. Lackman
10/18/2004 11:58:25 AM
Hello,

I have created a MemoryStream that is holding Binary Data. How do I get the
Data out of the Memory Stream into a file on my hard drive. All the
examples I have seen for a MemoryStream write the contents to the console.

Thanks
Chuck

Charles A. Lackman
10/18/2004 12:19:44 PM
Hello I am retrieve binary data from a web service and need to write it to
disk. It will be a setup file or replacement files I have made for
applications.

This is where I am lost

the memory stream is filled.

ms.Seek(0, SeekOrigin.Begin)
Dim MyWriter as StreamWriter
MyWriter = New StreamWriter("C:\Test.Setup")

ms.read
mywriter.write(ms)

ms.close
mywriter.close
This does not work, what am I missing,

Thanks
Chuck


[quoted text, click to view]

Charles A. Lackman
10/18/2004 12:22:23 PM
Thank You, Thank You, Thank You,

Chuck
:)
[quoted text, click to view]

Jay B. Harlow [MVP - Outlook]
10/18/2004 2:06:01 PM
Chuck,
You can use MemoryStream.ToArray to get the MemoryStream as an array of
bytes.

You can then use a FileStream to write this array of bytes to a file.

Alternatively you could read the MemoryStream from the beginning writing the
data to a FileStream...

However if your goal is to write Binary Data to a file, why not simply open
a FileStream directly instead of using an intermediate MemoryStream?

Hope this helps
Jay

[quoted text, click to view]

Arne Janning
10/18/2004 9:15:44 PM
Hi Charles!

"Charles A. Lackman" schrieb
[quoted text, click to view]

In addition to the possibilities Jay listed you can use the
MemoryStream.WriteTo()-Method:

Dim buffer As Byte() = New Byte() {1, 2, 3, 4, 5}
Dim ms As MemoryStream = New MemoryStream(buffer)
Dim st As FileStream = New FileStream( _
"C:\test.bin", FileMode.Create)
ms.WriteTo(st)
st.Close()
ms.Close()


Cheers

Arne Janning

Jon Skeet [C# MVP]
10/18/2004 10:23:11 PM
[quoted text, click to view]

One point here, apart from what the others have said: if you've got
binary data, you shouldn't use StreamWriter. Writers and Readers are
for text data. Streams are for binary data. Just use FileStream.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button