附加到txt文件会产生奇怪的字符

时间:2016-03-05 19:41:48

标签: c# text encoding

我的代码是:

File.AppendAllText(
       @"C: \Users\aalig\Downloads\stok.txt", 
       "text content" + Environment.NewLine, 
       Encoding.UTF8);

但是在写文本文件看起来之后 - 原始文本首先正确(预期),但后面是象形文字而不是“文本内容”:

Image of invalid text

1 个答案:

答案 0 :(得分:2)

源文件具有不同的编码(不是代码指定的UTF8)。当AppendAllText按照请求添加UTF8文本时,它将附加UTF8编码的字符串。当用另一种编码(即UTF16)读取这样的字节序列时,它将被解释为不同的Unicode字符集。

修正:

  1. 在附加文本时使用文件编码(如果您知道的话)
  2. 首先阅读所有文本,然后使用您选择的编码重写文件。
  3. 产生无效结果的示例:

    string path = @"e:\temp\MyTest.txt";
    File.WriteAllText(path, "Hello and Welcome" + Environment.NewLine, Encoding.Unicode);
    // Note that AppendAllText uses different encoding than WriteAllText
    // To correct - specify the same Encoding.Unicode (option 1)
    File.AppendAllText(path, "text content" + Environment.NewLine, Encoding.UTF8);
    
    Console.WriteLine(File.ReadAllText(path));
    

    结果

    Hello and Welcome
    整瑸挠湯整瑮਍
    

    读取整个文件并附加文本的示例(选项2)

    File.WriteAllText(path, 
       File.ReadAllText(path) 
       + Environment.NewLine 
       + newContentToAdd);     
    
相关问题