C#使用BinaryReader类读取二进制文件

348 篇文章 0 订阅

C#使用BinaryReader类读取二进制文件

11440人阅读 评论(0) 收藏 举报
本文章已收录于:
分类:

C#使用BinaryReader类读取二进制文件


BinaryReader类用来读取二进制数据,其读取数据的方法很多,常用方法如下:

Close():关闭BinaryReader对象;

Read():从指定流读取数据,并将指针迁移,指向下一个字符。

ReadDecimal():从指定流读取一个十进制数值,并将在流中的位置向前移动16个字节。

ReadByte():从指定流读取一个字节值,并将在流中的位置向前移动一个字节。

ReadInt16():从指定流读取两个字节带符号整数值,并将在流中的位置向前移动两个字节。

ReadInt32():从指定流读取两个字节带符号整数值,并将在流中的位置向前移动两个字节。

ReadString():从指定流读取字符串,该字符串的前缀为字符串长度,编码为整数,每次7比特。

BinaryReader类创建对象时必须基于所提供的流文件。

使用BinaryReader类读取二进制数据实例:

我们使用上节写入的文本文件

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Text;  
  5. public class MyClass  
  6. {  
  7. public static void Main()  
  8. {  
  9. string path = @"C:\123.txt";  
  10. FileStream fs = new FileStream(path, FileMode.Open,FileAccess.Read);  
  11. BinaryReader br = new BinaryReader(fs);  
  12. char cha;  
  13. int num;  
  14. double doub;  
  15. string str;  
  16. try  
  17. {  
  18. while (true)  
  19. {  
  20. cha = br.ReadChar();  
  21. num = br.ReadInt32();  
  22. doub = br.ReadDouble();  
  23. str = br.ReadString();  
  24. Console.WriteLine("{0},{1},{2},{2}", cha, num, doub, str);  
  25. }  
  26. }  
  27. catch (EndOfStreamException e)  
  28. {  
  29. Console.WriteLine(e.Message);  
  30. Console.WriteLine("已经读到末尾");  
  31. }  
  32. finally  
  33. {  
  34. Console.ReadKey();  
  35. }  
  36. }  
  37. }  
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();
}
}
}


我们利用创建的文件作为源文件,创建了FileStream对象,并基于该对象创建了BinaryReader对象,调用BinaryReader对象的读取文件内容的各个方法,分别读出源文件中的字符,整型数据,双精度数据和字符串。由于不确定要遍历多少次才能读取文件末尾,出现EndStreamException异常。循环内读取的数据被输出到控制台。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值