2017-04-26 139 views
0

我有這個簡單的代碼:C#寫入文件時使用UTF8

using (var sw = new StreamWriter(path + kat + "/" + namec, true, Encoding.UTF8)) 
{ 
    sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport); 
} 

我使用Selenium網絡驅動程序從丹麥網站,例如鏈接下載數據:http://www.visitdenmark.dk/da/danmark/danhostel-roenne-gdk614558

然後我把它保存在.csv文件,但我仍然有這樣的角色,而不是這個角色。正如你所看到的,我設置了Encoding.UTF8當我設置bool append爲false時,它也變得更有趣了,那麼一切都是正常的,但它不會幫助我,因爲我需要用新數據追加該文件。我怎樣才能解決這個問題 ?

回答

1

對於丹麥語,您應該使用windows-1252(或Encoding.GetEncoding(1252))而不是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")); 
} 
+0

還是一樣http://prntscr.com/f16v7b當我做'MessageBox.Show(namex);'以.csv文件中插入之前顯示我正常的字符,以便插入之前一切正常。任何線索? – mdieod

+0

@mdieod你能測試這段代碼是否能產生正確的結果嗎? https://pastebin.com/L947k1Nw – Xiaoy312

+0

我只是運行你的代碼,並得到相同的結果http://prntscr.com/f176iv – mdieod