BinaryReader和BinaryWriter类
如果正在处理二进制文件,则可以使用BinaryReader和BinaryWriter类。下面的示例从一个文件中读取二进制数据并且将这些数据写入另一个文本文件,同时建立该文件的副本。
- using System;
- using System.IO;
- namespace BinaryReaderBinaryWriter
- {
- class Program
- {
- static void Main(string[] args)
- {
- string filePath = @"D:/temp/textfile.txt";
- string filePathCopy = @"D:/temp/textfile_copy.txt";
- try
- {
- //---open files for reading and writing---
- FileStream fs1 = File.OpenRead(filePath);
- FileStream fs2 = File.OpenWrite(filePathCopy);
- BinaryReader br = new BinaryReader(fs1);
- BinaryWriter bw = new BinaryWriter(fs2);
- //---read and write individual bytes---
- for (int i = 0; i <= br.BaseStream.Length - 1; i++)
- bw.Write(br.ReadByte());
- //---close the reader and writer---
- br.Close();
- bw.Close();
- }
- catch (IOException ex)
- {
- Console.WriteLine(ex.Message);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- Console.ReadLine();
- }
- }
- }