为什么空白出现在我的 C# TextWriter 文件的末尾?

Why does whitespace appear at the end of my C# TextWriter file?

我使用 TextWriter C# 创建了一个文本文件,在最终创建时,该文本文件通常在文件末尾有多行空格。构成文件的任何字符串对象中都不包含空格,我不知道是什么原因造成的。文件越大,空白就越多。

我已经尝试了各种测试来查看空格是否根据字符串的内容出现,但事实并非如此。即我已经确定了空白开始的行数,并将字符串更改为完全不同的内容,但空白仍然存在。

//To start:
MemoryStream memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);

//Loop through records & create a concatenated string object
string strUTL1 = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", strUTL1_1, strUTL1_2, strUTL1_3, strUTL1_4, strUTL1_5, strUTL1_6, strUTL1_7, strUTL1_8);

//Add the line to the text file
tw.WriteLine(strUTL1);

//Once all rows are added I complete the file
tw.Flush();
tw.Close();


//Then return the file
return File(memoryStream.GetBuffer(), "text/plain", txtFileName);

我不想在完成后操作文件(例如替换空格),因为这可能会导致其他问题。该文件将与第三方交换,需要准确格式化。

感谢您的帮助。

使用 ToArray() instead of GetBuffer(),因为缓冲区比需要的大。

情况经常如此。 类 或使用缓冲区的函数通常会保留一定大小的内存来保存数据。然后该函数将 return 一个值,表示已将多少字节写入缓冲区。然后,您只能使用缓冲区的前 n 个字节。

MSDN 引用:

For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer() is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray() method; however, ToArray() creates a copy of the data in memory.

作为the doc for MemoryStream.GetBuffer explains:

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.

使用 .ToArray()(它将分配一个大小合适的新数组),或者您可以使用从 .GetBuffer() 返回的缓冲区,但您需要检查 .Length查看其中有多少有效字节。

GetBuffer() returns 分配的所有内存,几乎总是比您实际写入的内存多。

我是否建议改用 Encoding.UTF8.GetBytes(...)

string strUTL1 = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", strUTL1_1, strUTL1_2, strUTL1_3, strUTL1_4, strUTL1_5, strUTL1_6, strUTL1_7, strUTL1_8);

var bytes = Encoding.UTF8.GetBytes(strUTL1);

return File(bytes, "text/plain", txtFileName);