C# C使用UTF8写入文件

C# C使用UTF8写入文件,c#,selenium,selenium-webdriver,utf-8,C#,Selenium,Selenium Webdriver,Utf 8,我有一个简单的代码: using (var sw = new StreamWriter(path + kat + "/" + namec, true, Encoding.UTF8)) { sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport); } 我使用Selenium Web驱动程序从丹麦网站下载数据,示例链接: 然后我将

我有一个简单的代码:

using (var sw = new StreamWriter(path + kat + "/" + namec, true, Encoding.UTF8))
{
    sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport);
}
我使用Selenium Web驱动程序从丹麦网站下载数据,示例链接:

然后我将其存储在.csv文件中,但仍然有像这样的字符Ă而不是这个ø。正如您所看到的,我设置了Encoding.UTF8,当我将bool append设置为false时,它变得更加有趣,然后一切都正常,但这对我没有帮助,因为我需要用新数据附加该文件。我怎样才能解决这个问题

对于丹麦语,您应该使用windows-1252or,Encoding.GetEncoding1252而不是UTF-8

编辑:

缺少BOM表问题导致Excel无法正确读取文件

// notice we are creating a new file here
using (var writer = new StreamWriter(path, false, Encoding.UTF8))
{
    // Add a BOM in the beginning of the file
    var preamble = Encoding.UTF8.GetPreamble();
    writer.BaseStream.Write(preamble, 0, preamble.Length);

    // write data...
    writer.WriteLine(string.Join(",", "Danhostel Rønne", "Arsenalvej 12 3700 Rønne"));
}

// when you write the same file again, you don't need to append the BOM again
using (var writer = new StreamWriter(path, true, Encoding.UTF8))
{
    // write more data...
    writer.WriteLine(string.Join(",", "Danhostel Rønne", "Arsenalvej 12 3700 Rønne"));
}

当我使用MessageBox.Shownamex时仍然是一样的;在插入.csv文件之前,它会显示正常字符,所以在插入之前,一切都是正常的。有什么线索吗?@mdieod您能测试一下这段代码是否生成了正确的结果吗?使用记事本而不是Excel打开csv文件时会发生什么情况?如果在Excel中转到“数据->来自文本”,并且选择了错误的编码,则它会读取错误的位并显示错误的字符。@Quantic当我尝试从文本导入数据时,它会自动设置Windows ANSI并正常工作。我还是不明白这对我有什么帮助?@mdieod似乎Excel没有正确打开文件。你能测试一下这个代码吗。我在文件的开头添加了BOM表。