我录制了一个包含一些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。
我想正确阅读。
这里的关键是将正确的信息传递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);
}
}
但是请注意,这是更容易使用foreach
与File.ReadLines("test.txt", Encoding.UTF8)
:
foreach(var line in File.ReadLines("test.txt", Encoding.UTF8))
{
Console.WriteLine(line);
}