结合着一段程序,来了解以下BinaryWriter的功能
class Program
{
static void Main(string[] args)
{
string filePath = "test.dat";
//create the file
using (BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate)))
{
bw.Write("This is string1");
bw.Write(1);
bw.Write(true);
bw.Write(false);
bw.Write("This is string2");
bw.Write("This is string3");
bw.Write(2);
bw.Write(257);
bw.Write(true);
bw.Write(false);
}
//since the file has been created, open it this time, and then write some contents
//the existing content is not deleted before writting,but just begin to write at the file beginning.
using(BinaryWriter bw = new BinaryWriter(File.Open(filePath,FileMode.OpenOrCreate)))
{
bw.Write("This is string1");
bw.Write(1);
bw.Write("This is string2");
bw.Write("This is");
bw.Write(2);
}
//since the string length is recorded at the beginning of the string
//if we put the read point to the middle of the string and then try to read string
//EndOfStreamException is thrown
using (BinaryReader br = new BinaryReader(File.Open(filePath, FileMode.OpenOrCreate)))
{
br.BaseStream.Seek(3, SeekOrigin.Begin);
try
{
string a = br.ReadString();
}
catch (EndOfStreamException eos)
{
Console.WriteLine(eos.ToString());
}
}
}
}
上述程序一共分成三块:
第一块创建一个文件,并用BinaryWriter写入一些信息;
第二快打开刚才创建的文件,再用BinaryWriter写入一些信息;
第三块打开文件,然后把文件指针向后移动3个字节,然后试着读取字符串;
下面是用WinHex看到的文件内容:
Stage1:
Stage2:
Stage3:
结论:
a)BinaryWriter在写入字符串时,会在字符串前边加上字符串的长度。参照Stage1中图片,0F就是后面跟着一个长度为15的字符串。
b)读取什么样的内容要靠程序员来决定,文件本身不知道如何分割字节。即开发人员必须自己规划ReadString,ReadInt等,否则程序会报错
c)32位的整数,在二进制文件中“字节内正序,字节间反序”。 就一个字节的高四位在前,低四位在后。 但32位的4个字节,则是低字节位在前,高字节位在后。
4)用FileMode.OpenOrCreate 打开二进制文件,并写入时,并没有先把旧有内容清空,只是前部分字节被覆盖而已,后面内容不受影响。 但很有可能文件的格式已经被破坏了。 如Stage2中“tring3”前面就没有了字符串的长度信息
5)由于字符串的长度信息在字符串的前面,所以读取字符串必须从长度位置开始读取,否则就会因获得不要正确的长度而导致无法停止读取。 如Stage3,将文件指针向前移动三位,然后读取,报错