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?
Vadym Stetsyak - 02 Oct 2006 22:54 GMT
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
Tim Johnson - 03 Oct 2006 00:10 GMT
Thanks, that seems to do the trick!
Tim
> Hello, Tim!
> You wrote on Mon, 2 Oct 2006 14:36:02 -0700:
[quoted text clipped - 17 lines]
> With best regards, Vadym Stetsyak.
> Blog: http://vadmyst.blogspot.com
Jon Skeet [C# MVP] - 02 Oct 2006 23:58 GMT
> 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.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too