Search code examples
c#asp.net-corestream.net-8.0memorystream

Write and read string from MemoryStream


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


Solution

  • 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.