将 .csv(ANSI) 转换为 .csv(UTF-8)

convert .csv(ANSI) into .csv(UTF-8)

我的电脑有日文环境。所以我需要一个程序来将我的 .csv ANSI 转换为 .csv UTF-8。我尝试使用此代码:

string st = File.ReadAllText("C:\Users\user\Desktop\train1.csv");            
System.IO.File.WriteAllText("C:\Users\user\Desktop\train2.csv",st.ToString(), Encoding.UTF8); 

文件train2.csv创建成功,但是,由于转换,文本变得不可读。执行此操作的正确方法是什么?

我假设未正确检测到输入文件编码,因此您应该定义它

string st = File.ReadAllText("C:\Users\user\Desktop\train1.csv", Encoding.Default); //ANSI

Documentation:

This method attempts to automatically detect the encoding of a file based on the presence of byte order marks. Encoding formats UTF-8 and UTF-32 (both big-endian and little-endian) can be detected.

Use the ReadAllText(String, Encoding) method overload when reading files that might contain imported text, because unrecognized characters may not be read correctly.

StreamReaderclass可以支持读取带编码的文件

StreamReader st = new StreamReader("C:\Users\user\Desktop\train1.csv", 
                                                 System.Text.Encoding.ASCII);

之后就可以根据StreamWriter

将数据写入文件