处理二进制文件(BinaryReader和BinaryWriter类 )

来源:互联网 发布:淘宝优惠券定向发放 编辑:程序博客网 时间:2024/06/05 05:02

 

BinaryReader和BinaryWriter类 

如果正在处理二进制文件,则可以使用BinaryReader和BinaryWriter类。下面的示例从一个文件中读取二进制数据并且将这些数据写入另一个文本文件,同时建立该文件的副本。

 

view plaincopy to clipboardprint?
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace BinaryReaderBinaryWriter  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             string filePath = @"D:/temp/textfile.txt";  
  11.             string filePathCopy = @"D:/temp/textfile_copy.txt";  
  12.             try  
  13.             {  
  14.                 //---open files for reading and writing---  
  15.                 FileStream fs1 = File.OpenRead(filePath);  
  16.                 FileStream fs2 = File.OpenWrite(filePathCopy);  
  17.   
  18.                 BinaryReader br = new BinaryReader(fs1);  
  19.                 BinaryWriter bw = new BinaryWriter(fs2);  
  20.   
  21.                 //---read and write individual bytes---  
  22.                 for (int i = 0; i <= br.BaseStream.Length - 1; i++)  
  23.                     bw.Write(br.ReadByte());  
  24.   
  25.                 //---close the reader and writer---  
  26.                 br.Close();  
  27.                 bw.Close();  
  28.             }  
  29.             catch (IOException ex)  
  30.             {  
  31.                 Console.WriteLine(ex.Message);  
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                 Console.WriteLine(ex.Message);  
  36.             }  
  37.   
  38.             Console.ReadLine();  
  39.         }  
  40.     }  
  41. }  

 

 

原创粉丝点击