Problems writing MemoryStream to disk

G

Guest

I offer 2 Write methods in my class, one that writes to and returns a
MemoryStream, and one that writes to a file. The 2nd one just calls the 1st
one, then I want to write the returned ms to disk. I tried 2 different
approaches, with the problems indicated:

(1)
using (FileStream fs = File.OpenWrite(fileName))
{
fs.Write(ms.GetBuffer(), 0, (int)ms.Position);
}

==> This approach wouldn't write out the final block of text (about 500
bytes), even though I did a Flush on the ms.

(2)
byte[] array = ms.ToArray();
using (MemoryStream ms2 = new MemoryStream(array))
{
using (FileStream fs = File.OpenWrite(fileName))
{
fs.Write(array, 0, ms2.Length);
}
}
==> This approach would write out an extra 200K of garbage text!

So I had to resort to this uglier brute-force method which at least works:

byte[] array = ms.ToArray();
using (MemoryStream ms2 = new MemoryStream(array))
{
using (StreamReader sr = new StreamReader(ms2))
{
using (StreamWriter sw = new StreamWriter(fileName, false))
{
string line;
while ( (line=sr.ReadLine()) != null)
sw.WriteLine(line);
}
}
}

Any ideas why one of the first more compact approaches would not be reliable?
 
V

Vadym Stetsyak

Hello, Tim!
You wrote on Mon, 2 Oct 2006 14:36:02 -0700:

[skipped]

TJ> Any ideas why one of the first more compact approaches would not be
TJ> reliable?

You can try this:

MemoryStream memStream; //memory stream which contents
//will be written to the file

using (FileStream fs = File.OpenWrite(fileName))
{
memStream.WriteTo(fs);
fs.Close();
}


With best regards, Vadym Stetsyak.
Blog: http://vadmyst.blogspot.com
 
J

Jon Skeet [C# MVP]

Tim Johnson said:
I offer 2 Write methods in my class, one that writes to and returns a
MemoryStream, and one that writes to a file. The 2nd one just calls the 1st
one, then I want to write the returned ms to disk. I tried 2 different
approaches, with the problems indicated:

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top