温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to read unicode character "degree sign" from a UTF-8 encoded text file in c#?
c# file-read

其他 - 如何在C#中从UTF-8编码的文本文件中读取Unicode字符“度数”?

发布于 2020-03-27 10:42:30

我录制了一个包含一些Unicode字符的文本文件:例如,“度号” \ u00b0和“ SUPERSCRIPT TWO” \ u00b2。

然后,我想使用c#StreamReader读取此文本文件。这些unicode字符无法正确读取。

文本文件包含以下行:

26,VehicleData Acceleration Z,m /s²,System.Single 27,VehicleData Angular Velocity about X,°/ s,System.Single

数据读取部分:

1. StreamReader indexReader = File.OpenText( filename + ".txt");
2. StreamReader indexReader = new StreamReader(filename + ".txt", System.Text.Encoding.Unicode);

...

数据分配部分:

for ( int i = 0; i < headerCount; i++ )
{
  string line = indexReader.ReadLine();
  string[] parameterHeader = line.Split( ',' );
  var next = new ReportParameters.ParameterInfoElement();
  next.parameterID = Int32.Parse( parameterHeader[ 0 ] );
  next.name = parameterHeader[ 1 ];
  next.units = parameterHeader[ 2 ];
  next.type = Type.GetType( parameterHeader[ 3 ] );

  _header.Add( next );
}

m /s²和°/ s将分别读取为m /s�和�/ s。

我想正确阅读。

查看更多

查看更多

提问者
JoKart15
被浏览
179
2019-07-03 21:44

这里的关键是将正确的信息传递Encoding给读者。因为您说的是UTF-8:

/* write a dummy file as raw UTF-8; this is just test data that looks like:
3
*/
File.WriteAllBytes("test.txt", new byte[] {
         0x31, 0xC2, 0xB0, 0x0D, 0x0A,
         0x32, 0xC2, 0xB2, 0x0D, 0x0A, 0x33 });

// use the TextReader API to consume the file
using (var reader = new StreamReader("test.txt", Encoding.UTF8))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

但是请注意,这是更容易使用foreachFile.ReadLines("test.txt", Encoding.UTF8)

foreach(var line in File.ReadLines("test.txt", Encoding.UTF8))
{
    Console.WriteLine(line);
}