先说下测试环境: 中文的XP + 英文的VS2008标准版
在测试StreamReader时遇到下面一问题,参照下面程序:
static void Main(string[] args)
{
TestReaderWriter trw = new TestReaderWriter();
trw.printFileInfo();
Console.Read();
}
class TestReaderWriter
{
private string filePath = @"../data/data.txt";
internal void printFileInfo()
{
string line = null;
int index = 0;
using (StreamReader sr = new StreamReader(this.filePath,Encoding.Default))
{
Console.WriteLine("StreamReader sr = new StreamReader(this.filePath,Encoding.Default)");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine("{0}:{1}", ++index, line);
}
}
using (StreamReader sr = new StreamReader(this.filePath))
{
index = 0;
Console.WriteLine("StreamReader sr = new StreamReader(this.filePath)");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine("{0}:{1}", ++index, line);
}
}
using (StreamReader sr = new StreamReader(this.filePath,Encoding.Unicode))
{
index = 0;
Console.WriteLine("StreamReader sr = new StreamReader(this.filePath,Encoding.Unicode)");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine("{0}:{1}", ++index, line);
}
}
using (StreamReader sr = new StreamReader(this.filePath, Encoding.UTF32))
{
index = 0;
Console.WriteLine("StreamReader sr = new StreamReader(this.filePath,Encoding.UTF32)");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine("{0}:{1}", ++index, line);
}
}
using (StreamReader sr = new StreamReader(this.filePath, Encoding.UTF8))
{
index = 0;
Console.WriteLine("StreamReader sr = new StreamReader(this.filePath,Encoding.UTF8)");
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine("{0}:{1}", ++index, line);
}
}
Console.WriteLine("Done!");
}
}
其中准备有一data.txt文件,文件编码为ANSI,内容如下:
读取结果如下:
结论:
a)系统默认的编码方式为UTF8
b)读取文件时,选用合适的编码方式很重要。因为文件本身就是一串Byte流,如果没有合适的编码,程序就不知道如何把Byte流组装为合适的字符串信息。