初识IO流——二进制文件的读和写操作

  C#中,二进制文件的写和读操作分别由BinaryWrite类和BinaryReader类实现,它们都所属与System.IO命名空间。

  BinaryWriter类以二进制的形式将基元写入流,并支持用特定的编码写入字符串。

  BinaryReader类用特定的编码将基元数据类型读作二进制值。

  根据BinaryWriter类和BinaryReader类的实现写和读过程,其实可以将二者理解为一个"互逆"的过程。

 

  示例:分别用BinaryWrite类和BinaryReader类实现二进制文件的写操作和读操作。

 

  (1)BinaryWrite类实现写入操作:

 1 public void DoWrite(string str)
 2         {
 3             /*文件在项目中的相对于根目录的位置*/
 4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
 5 
 6             /*获取项目的根目录*/
 7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
 8 
 9             FileStream filestream = new FileStream(Full_path, FileMode.Append, FileAccess.Write);
10 
11             using (BinaryWriter writer = new BinaryWriter(filestream))
12             {
13 
14                 writer.Write(str);
15 
16             }
17 
18         }

 

  (2)BinaryReader类实现文件的读取操作:

 1 public string DoRead()
 2         {
 3             /*文件在项目中的相对于根目录的位置*/
 4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
 5 
 6             /*获取项目的根目录*/
 7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
 8 
 9             /*存储结果*/
10             string Read_text = string.Empty;
11 
12             FileStream filestream = new FileStream(Full_path, FileMode.Open, FileAccess.Read);
13 
14             using (BinaryReader reader = new BinaryReader(filestream))
15             {
16 
17                 /*判断是否读到结尾处*/
18                 while (reader.PeekChar() != -1)
19                 {
20 
21                     Read_text += reader.ReadString();
22 
23                 }
24 
25                 return Read_text;
26             }
27 
28         }

 

   

转载于:https://www.cnblogs.com/SunshineAgain/p/5703480.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值