如何在C#.Net中获取UTF-8的CSV文件?

SuS*_*nda 15 c# csv encoding utf-8

我想制作UTF-8编码的CSV文件.现在,我的CSV文件无法显示日文字体.我想要C#代码来解决这个问题.

Bee*_*Guy 31

SuSanda,
我不确定您当前的代码或您尝试保存的实际文本,但这可能会让您朝着正确的方向前进.

using(var sw = new StreamWriter("testfile_utf8.csv", false, Encoding.UTF8))
{
    sw.WriteLine("???");
}
Run Code Online (Sandbox Code Playgroud)

如果您在Excel中打开该文件,它将按预期显示日语文本.
如果不包含Encoding.UTF8参数,则会显示乱码.

我希望这就是你要找的东西.

  • 使用:`new UTF8Encoding(false)`而不是`Encoding.UTF8`如果你想避免BOM符号 (3认同)

jAn*_*oni 6

此代码有助于从csv文件发送文本,以将其另存为编码的csv文件。要使用它,请按如下所示进行调用并保存。

GetCSVFileContent(“ Your_CSV_FileName”)

protected byte[] GetCSVFileContent(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
            }
            string allines = sb.ToString();


            UTF8Encoding utf8 = new UTF8Encoding();


            var preamble = utf8.GetPreamble();

            var data = utf8.GetBytes(allines);


            return data;
        }
Run Code Online (Sandbox Code Playgroud)