
本帖最后由 wulangxiong 于 2013-1-29 17:58 编辑
System.IO 还为我们提供了BinaryReader 和BinaryWriter 类用于按二进制模式读
写文件它们提供的一些读写方法是对称的比如针对不同的数据结构BinaryReader
提供了ReadByte ReadBoolean ReadInt ReadInt16 ReadDouble ReadString 等方法
而BinaryWriterz 则提供了WriteByte WriteBoolean WriteInt WriteInt16 WriteDouble
WriteString 方法
下面我们举一个通讯录的例子来说明BinaryReader 和BinaryWriter 类是如何使用
的。
using System;using System.IO;struct Record{publicstring name;
publicUInt16 age;
publicstring phone;
publicstring address;
};//通讯录的记录格式classPhoneBook
{FileStreamf_srm;strings_filename;Recordm_record;publicPhoneBook(string filename)
{s_filename= filename;
}publicintOpen()
{//显示初始化界面Console.WriteLine("1: List Record");Console.WriteLine("2: Add New Record");Console.WriteLine("3: Erase Record");Console.WriteLine("0: Exit");inti = Console.Read() -
'0';returni;
}publicvoidAddNew()
{//向通讯录中添加记录try{f_srm =newFileStream(s_filename,FileMode.OpenOrCreate);
}catch{Console.WriteLine("PhoneBookError!");return;}BinaryWriter pw =newBinaryWriter(f_srm);
pw.Seek(0,SeekOrigin.End);string s_temp;Console.Write("Name:");Console.ReadLine();m_record.name = Console.ReadLine();pw.WriteString(m_record.name);reenter:Console.Write("Age: ");s_temp = Console.ReadLine();try{m_record.age = s_temp.ToUInt16();}catch{Console.WriteLine("The formatof age is error,please ReEnter");gotoreenter;
}pw.Write(m_record.age);Console.Write("PhoneNumber: ");m_record.phone = Console.ReadLine();pw.WriteString(m_record.phone);Console.Write("Address:");m_record.address = Console.ReadLine();pw.WriteString(m_record.address);f_srm.Close();}publicvoidList()
{//浏览所有记录try{f_srm =newFileStream(s_filename,FileMode.Open);
}catch{Console.WriteLine("PhoneBookError!");return;}BinaryReader pr =newBinaryReader(f_srm);
Console.WriteLine("Name AgePhone Number Address");Console.WriteLine("***************************************");while(true){try{m_record.name = pr.ReadString();m_record.age = pr.ReadUInt16();m_record.phone = pr.ReadString();m_record.address = pr.ReadString();}catch{return;}Console.WriteLine("{0,-9}{1,-6}{2,-18}{3}",m_record.name,m_record.age,m_record.phone,m_record.address);}f_srm.Close();}publicvoidErase()
{//清空所有记录try{f_srm =newFileStream(s_filename,FileMode.Create);
}catch{Console.WriteLine("PhoneBook Error!");return;}f_srm.Close();Console.WriteLine("Now the book is empty!");}}classTest
{publicstaticvoidMain()
{PhoneBook pbook =newPhoneBook(
"c:\\c#\\file\\Phone.book");inti = pbook.Open();
switch(i){case1:
pbook.List();break;case2:
pbook.AddNew();break;case3:
pbook.Erase();}}}}其中有这么一条语句
Console.WriteLine("{0,-9}{1,-6}{2,-18}{3}",m_record.name,
m_record.age,m_record.phone,m_record.address);
它表示对输出进行格式化{} 中使用的第二个数表示输出占据的屏幕位数正
数表示从右边起计而负数表示从左边起计。