【问题标题】:How to read unicode character "degree sign" from a UTF-8 encoded text file in c#?如何从 c# 中的 UTF-8 编码文本文件中读取 unicode 字符“度数符号”?
【发布时间】:2019-07-03 13:14:22
【问题描述】:

我录制了一个包含一些 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。

我想好好读一下。

【问题讨论】:

  • 如果文件是用UTF-8编码的,你为什么要传入Encoding.Unicode,它是little-endian UTF-16?这不会弄错一切吗?您是否尝试过传入Encoding.UTF8
  • 另外:您能确认一下文件中的实际字节数吗? \u00b0 的 UTF-8 是 C2-B0,同样\u00b2 是 C2-B2 - 所以如果这些不是你拥有的字节,它不是 UTF-8。如果这些您拥有的字节,那么告诉系统,通过将Encoding.UTF8 传递到这些API 中
  • 注意两个不同的字形如何产生相同的“�”字符。您实际上正在使用 Encoding.Default 读取文件,并且您获得了 U+FFFD 的 utf8 编码。损坏的文件,您需要与编写该文件的代码的程序员取得联系。
  • 我猜是原始代码将字符串写入文件。该字符串是 UTF-16 而不是 UTF-8。那么UTF-16编码的txt文件中的基本拉丁字符就可以通过UTF-8编码进行streamReader了。但特殊字符会损坏。

标签: c# file-read


【解决方案1】:

这里的关键是将正确的Encoding 传递给读者;既然你说是UTF-8:

/* write a dummy file as raw UTF-8; this is just test data that looks like:
1°
2²
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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2013-01-31
    • 2017-09-06
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多