1

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

3
  • 1
    LIkely because the StreamWriter is still open and did not flush its buffer. Try usng StreamWriter.Close first. Commented Jul 2 at 3:42
  • 1
    As @TimRoberts said you have to flush the write just right after sw.WriteLine, you can do like this ` sw.Flush();` Commented Jul 2 at 3:47
  • Yes that works. I forgot that code. Thanks
    – DooDoo
    Commented Jul 2 at 3:51

1 Answer 1

1

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?

Based on your error message the issue you're encountering arises because when you write to a MemoryStream using a StreamWriter, it doesn't immediately flush the contents to the underlying stream (MemoryStream in this case).

To ensure that the data is written to the MemoryStream, you need to explicitly flush the StreamWriter after writing to it.

You can also try following way as well:

 byte[] allBytes = System.IO.File.ReadAllBytes(filePath);
 using (MemoryStream memStream = new MemoryStream())
 {
     
     memStream.Write(allBytes, 0, allBytes.Length);
     string additionalText = "This is some additional text";
     byte[] additionalBytes = Encoding.UTF8.GetBytes(additionalText);
     memStream.Write(additionalBytes, 0, additionalBytes.Length);

    
     memStream.Position = 0;

     // Read entire MemoryStream as a string
     using (StreamReader sr = new StreamReader(memStream))
     {
         string result = sr.ReadToEnd();
         Console.WriteLine(result);
     }
 }

Output:

enter image description here

Note: I have tested with .NET 8 app and asp.net core app both works as expected.

Not the answer you're looking for? Browse other questions tagged or ask your own question.