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?
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?