【问题标题】:Streamwriter adding characters to first lineStreamwriter 将字符添加到第一行
【发布时间】: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


【解决方案1】:

我遇到了这个确切的问题,并且(感谢这个问题的 cmets)将这些字符识别为 Byte Order Mark 然后允许我使用以下代码更改编码以排除 BOM:

using (StreamWriter sw = new StreamWriter(fileName, true, new UTF8Encoding(false), BufferSize))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 2012-02-12
    • 2013-05-11
    • 2013-04-17
    • 2016-08-01
    • 2016-08-11
    • 2019-03-17
    相关资源
    最近更新 更多