【发布时间】:2015-05-14 23:55:02
【问题描述】:
我在 c# 中做一些相当简单的事情,将字符串列表写入文本文件。我的写子是:
public static bool TextToFile(string fileName, List<string> inString) {
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
try {
if (File.Exists(fileName))
File.Delete(fileName);
const int BufferSize = 65536; // 64 Kilobytes
using (StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8, BufferSize)) {
if (inString.Count > 0) {
foreach (string str in inString) {
sw.WriteLine(str);
}
}
else
sw.WriteLine("");
}
return true;
}
catch {
return false;
}
}
虽然我在第一行的开头得到了额外的东西。 它不会在常规文本编辑器中显示,但是当我在 ultraedit 中打开并进入十六进制模式时,我看到了这个:
我的读取文本文件的程序确实看到了这些字符,并把它弄糊涂了。 我的字符串列表非常干净。 我有时会编写 100 mb 的文本文件,因此将缓冲区设置为 64k,但我尝试将其保留为默认值,结果相同。 我在win7 64位,使用VS 2013。
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
我刚刚注意到,如果我将生成的文本文件保存为 ansi 编码,那么奇怪的文本就会消失。然后我尝试保存回 utf-8,它又回来了。这是正确的行为吗?我从不想在文本文件中隐藏字符...
-
确实是 BOM。我应该把它留在那里吗?
-
我明白了,就像这样:New StreamWriter("Foobar.txt", False, utf8WithoutBom) 一旦你知道了关键字,就会在这上面发表其他几篇文章......thx
标签: c# .net streamwriter