C#使用BinaryReader类读取二进制文件
BinaryReader类用来读取二进制数据,其读取数据的方法很多,常用方法如下:
Close():关闭BinaryReader对象;
Read():从指定流读取数据,并将指针迁移,指向下一个字符。
ReadDecimal():从指定流读取一个十进制数值,并将在流中的位置向前移动16个字节。
ReadByte():从指定流读取一个字节值,并将在流中的位置向前移动一个字节。
ReadInt16():从指定流读取两个字节带符号整数值,并将在流中的位置向前移动两个字节。
ReadInt32():从指定流读取两个字节带符号整数值,并将在流中的位置向前移动两个字节。
ReadString():从指定流读取字符串,该字符串的前缀为字符串长度,编码为整数,每次7比特。
BinaryReader类创建对象时必须基于所提供的流文件。
使用BinaryReader类读取二进制数据实例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
public class MyClass
{
public static void Main()
{
string path = @"C:\123.txt";
FileStream fs = new FileStream(path, FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
char cha;
int num;
double doub;
string str;
try
{
while (true)
{
cha = br.ReadChar();
num = br.ReadInt32();
doub = br.ReadDouble();
str = br.ReadString();
Console.WriteLine("{0},{1},{2},{2}", cha, num, doub, str);
}
}
catch (EndOfStreamException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("已经读到末尾");
}
finally
{
Console.ReadKey();
}
}
}