简体   繁体   English

通过 StringWriter 写入 MemoryStream 会将空字符添加到流中

[英]Writing to a MemoryStream via a StringWriter adds null characters to stream

I have some code in C# where I am trying to write to a MemoryStream via a StringWriter example code:我在 C# 中有一些代码,我试图通过 StringWriter 示例代码写入 MemoryStream:

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.当我检查stream的内容时,我看到 .NET Framework 已将额外的0字节添加到缓冲区的末尾以使其达到 256 字节。 I can not find anything in the MSDN help and it is puzzling.我在 MSDN 帮助中找不到任何内容,这令人费解。

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)我宁愿使用流编写器也不愿构建字符串然后调用Encoding.UTF8.GetBytes(value)

I have tried using a StringBuilder as an intermediary step but it still adds the extra characters to the end.我曾尝试使用 StringBuilder 作为中间步骤,但它仍然会在末尾添加额外的字符。

You're calling stream.GetBuffer() , which returns the underlying buffer the stream writes to - which is almost always larger than the stream.您正在调用stream.GetBuffer() ,它返回流写入的底层缓冲区——它几乎总是比流大。 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.您可以使用stream.GetBuffer()也可以考虑流长度,并有效地忽略超过该长度的任何字节 - 或者调用stream.ToArray()而不是仅获取有效数据的副本作为新字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM