Please consider this scenario:
I want to read a file and then place its bytes to MemoryStream
and then write some strings to it and then immediately read entire MemotyStream
. For example I have a text file and it contains test
string. I wrote this code:
var allBytes = File.ReadAllBytes(<filePath>);
MemoryStream _mem = new MemoryStream(0);
_mem.Write(allBytes, 0, allBytes.Length);
StreamWriter sw = new StreamWriter(_mem);
sw.WriteLine("This is some text");
_mem.Position = 0;
using (StreamReader sr = new StreamReader(_mem))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
after I ran this code, I just get test
(file initial value) string and "This is some text"
didn't write to stream. How can I do that?
Thanks
StreamWriter
is still open and did not flush its buffer. Try usngStreamWriter.Close
first.sw.WriteLine
, you can do like this ` sw.Flush();`