C#.net 用 BinaryReader 和 BinaryWriter 读写文件

using System;
using System.IO;
using System.Text;

namespace FileTest
{
 class FileTest
 {
  static void Main(string[] args)
  {
   string sourceFileName = "F://source.txt";
   string targetFileName = "F://target.txt";
   FileStream readFileStream = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read);
   FileStream writeFileStream = new FileStream(targetFileName, FileMode.Open, FileAccess.Write);
   BinaryReader myBinRdr = new BinaryReader(readFileStream);
   BinaryWriter myBinWtr = new BinaryWriter(writeFileStream);

   try
   {
    File.Exists(sourceFileName); //判断源文件是否存在
   }
   catch(Exception e)
   {
    Console.WriteLine("Source File not existes ! {0}", e);
    Console.ReadLine();
    return;
   }

   try
   {
    byte fileContext;
    myBinRdr.BaseStream.Seek(5, SeekOrigin.Begin);
    myBinWtr.BaseStream.Seek(0, SeekOrigin.End);

    while(myBinRdr.BaseStream.Position < myBinRdr.BaseStream.Length)
    {
     fileContext = myBinRdr.ReadByte(); //按照字节读取文件
     myBinWtr.Write(fileContext); //写入文件
    }
   }
   catch(EndOfStreamException e)
   {
    Console.WriteLine(e);
    Console.ReadLine();
    return;
   }

   myBinRdr.Close();
   myBinWtr.Close();
   readFileStream.Close();
   writeFileStream.Close();

   Console.WriteLine("Successfully !");
   Console.ReadLine();


  }
 }
}
 

你可能感兴趣的:(C#.net 用 BinaryReader 和 BinaryWriter 读写文件)