-1

I have some code in C# where I am trying to write to a MemoryStream via a StringWriter example code:

using (MemoryStream stream = new MemoryStream())
{
  using (StreamWriter writer = new StreamWriter())
  {
    writer.WriteLine("SELECT");
    writer.WriteLine("\tT.*");
    writer.WriteLine("FROM");
    writer.WriteLine("\t[A Table] T");
    writer.WriteLine("WHERE");
    writer.WriteLine($"\tT.[Data Field] IN ({data})");
  }

   ....
  return new MemoryStream(stream.GetBuffer());
}

When I inspect the contents of stream I see that the .NET Framework has added extra 0 bytes to the end of the buffer to take it up to 256 bytes. I can not find anything in the MSDN help and it is puzzling.

To work around this (using the above example) I did the following:

string crlf = Environment.NewLine;


string value = $"SELECT{crlf}";
value += $"\tT.*{crlf}";
value += $"FROM{crlf}";
value += $"\t[A Table] T{crlf}";
value += $"WHERE{crlf}";
value += $"\tT.[Data Field] IN ({data})";


return new MemoryStream(Encoding.UTF8.GetBytes(value));

I would rather use a stream writer than to build up a string and then call Encoding.UTF8.GetBytes(value)

I have tried using a StringBuilder as an intermediary step but it still adds the extra characters to the end.

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • You should probably look at the documentation for `MemoryStream`. Especially to compare and contrast `GetBuffer` and `ToArray`. – Damien_The_Unbeliever Dec 16 '22 at 14:39
  • 6
    Side note, this looks like you're building an SQL Query using string concatenation. Highly consider parametrized statements. – gunr2171 Dec 16 '22 at 14:39
  • What is the purpose of doing this? What are you trying to achieve? – Tu deschizi eu inchid Dec 16 '22 at 15:53
  • @gunr2171 Normally I would use a parameterized query just in this use case I am building a query to select data and the source table and field is unknown at compile time. The code is only example code to describe my issue. – Emma Harris Dec 16 '22 at 16:20

1 Answers1

2

You're calling stream.GetBuffer(), which returns the underlying buffer the stream writes to - which is almost always larger than the stream. The buffer is expanded automatically when a write would go past the end of it.

You can either use stream.GetBuffer() but also take the stream length into account, and effectively ignore any bytes past that - or call stream.ToArray() instead to get a copy of just the valid data as a new byte array.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194