using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ch04
{
class Program
{
static string str_ascii = @"g:/testASCII.xml";
static string str_utf8 = @"g:/testUTF8.xml";
static void Main(string[] args)
{
Program.TestSaveUTF8();
Program.TestSaveASCII();
/*
* 用UTF8编码的StreamReader读取ASCII编码的文件,读出来的汉字字符不能识别
* 用UTF8编码的StreamReader读取UTF8编码的文件,读出来的汉字字符能识别
* 用ASCII编码的StreamReader读取ASCII编码的文件,读出来的汉字字符不能识别
* 用ASCII编码的StreamReader读取UTF8编码的文件,读出来的汉字字符能识别
*
* 总之,用UTF8编码存储的文件,无论用何种编码方式读取,都能正确识别其中的汉字
* 而用ASCII编码存储的文件,无论用何种编码方式读取,都不能正确识别其中的汉字
*
*/
Program.TestReadUTF8(str_ascii);
Program.TestReadUTF8(str_utf8);
Program.TestReadASCII(str_ascii);
Program.TestReadASCII(str_utf8);
}
static void TestSaveASCII()
{
string text = "<?xml version=/"1.0/"?>/n" + "<HEAD>head 测试一下</HEAD>/n";
using (FileStream fs = new FileStream(str_ascii, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fs,Encoding.ASCII))
{
sr.Write(text);
}
}
}
static void TestSaveUTF8()
{
string text = "<?xml version=/"1.0/"?>/n" + "<HEAD>head 测试一下</HEAD>/n";
using (FileStream fs = new FileStream(str_utf8, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fs, Encoding.UTF8))
{
sr.Write(text);
}
}
}
static void TestReadUTF8(string path)
{
Console.WriteLine("Reading "+path);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
string str = sr.ReadToEnd();
foreach (char s in str.ToCharArray())
{
Console.Write("{0}", s);
}
}
}
Console.WriteLine("Read end!");
}
static void TestReadASCII(string path)
{
Console.WriteLine("Reading " + path);
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs, Encoding.ASCII))
{
string str = sr.ReadToEnd();
foreach (char s in str.ToCharArray())
{
Console.Write("{0}", s);
}
}
}
Console.WriteLine("Read end!");
}
}
}