1.TextWriter(Reader)分别是对连续字符系列处理的编写器(读写器),来自System.IO
2.StringWriter(Reader)继承TextWriter(Reader),它主要是对字符串进行处理的类,样例如下:
TextWriter stringwriter = new StringWriter();
stringwriter.Write("你好,通过StringWriter写入,StringWriter继承TextWriter");
TextReader stringreader = new StringReader(stringwriter.ToString());
Console.WriteLine("从{0}——{1}", stringreader.GetType().Name, stringreader.ReadToEnd());
Console.WriteLine();
3.StreamWriter(Reader)也继承TextWriter(Reader),它主要是以流的形式处理数据,可以是记忆流,文件流,系列端口流以及媒体视频流等。例子:
using (TextWriter streamwriter = new StreamWriter("mytext.txt"))
{
streamwriter.Write("你好,通过StreamWriter写入,StreamWriter继承TextWriter");
}
TextReader streamreader = new StreamReader("mytext.txt");
Console.WriteLine("从{0}——{1}", streamreader.GetType().Name, streamreader.ReadToEnd());
Console.ReadLine();
4.BinaryWriter(Reader)不继承TextWriter(Reader),以二进制形式讲基元类型写入(读取),并支持特定的编码,其有广泛的支持形式,因为它以二进制方式读取写入。例子:
//BinaryWriter(Reader)
const string filename = "test.txt";
if (File.Exists(filename))
{
Console.WriteLine("{0}文件已存在!", filename);
}
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
string str = Environment.CurrentDirectory + @"QQ.EXE.lnk";
bw.Write(str);
bw.Close();
fs.Close();
//现在开始读取
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long size = br.BaseStream.Length;
byte[] bytesize = new byte[size];
bytesize = br.ReadBytes((int)size);
Console.WriteLine(bytesize.ToString());
br.Close();
fs.Close();
Console.ReadLine();
下面再示一例BinaryWriter写入XML信息例子:
const string filename = "XmlWriter1.xml";
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
XmlElement ee = xdoc.DocumentElement;
if (ee != null)
{
bw.Write(ee.OuterXml);
}
else
{
Console.WriteLine("获取对象失败!");
}
bw.Close();
fs.Close();