.NET實現(xiàn)簡易的文件增量備份程序

字號:


    這篇文章主要介紹了.NET實現(xiàn)簡易的文件增量備份程序,需要的朋友可以參考下
    .Net中提供了許多方便使用的方法,包括在處理文件中查找文件、拷貝文件等,今天實現(xiàn)的是通過簡易的程序?qū)崿F(xiàn)增量的備份文件。
    首先需要的是選擇備份源文件路徑SourcePath和備份目標文件路徑DestinationPath,然后通過StopWatch統(tǒng)計拷貝所耗費的時間。(注意:使用StopWatch需要添加 using System.Diagnostics命名空間,對文件的讀寫需要添加 using System.IO命名空間)。
    /// <summary>
    /// 增量備份函數(shù)方法
    /// </summary>
    /// <param name="SourcePath">備份源文件路徑</param>
    /// <param name="DestinationPath">備份目標文件路徑</param>
    public void CopyDirectory(String SourcePath, String DestinationPath){
      Stopwatch watch = new Stopwatch();
      watch.Start();   //開始計算時間
      // 檢查目標目錄是否以目錄分割字符結(jié)束如果不是則添加
      if (DestinationPath[DestinationPath.Length - 1] != Path.DirectorySeparatorChar)
      {
       DestinationPath += Path.DirectorySeparatorChar;
      }
      //判斷目標目錄是否存在如果不存在則新建
      if (!Directory.Exists( DestinationPath))
      {
       Directory.CreateDirectory(DestinationPath);
      }
      // 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個數(shù)組
      string[] fileList = Directory.GetFileSystemEntries(SourcePath);
      // 遍歷所有的文件和目錄
      foreach (string SourceFilename in fileList)
       {
        string filename = Path.GetFileName(SourceFilename);
         //先判斷文件在目標文件夾中是否存在
         if (File.Exists(DestinationPath + filename))
          {
           FileInfo oldFile = new FileInfo(SourceFilename);
           FileInfo newFile = new FileInfo(DestinationPath + filename);
           if (oldFile.LastWriteTime == newFile.LastWriteTime) 
            {
              continue;     //跳出本次循環(huán)
            }
           }      else {
           // 先當作目錄處理如果存在這個目錄就遞歸Copy該目錄下面的文件
           if (Directory.Exists(SourceFilename))
            {
              CopyDirectory(SourceFilename, DestinationPath + filename);
            }// 否則直接Copy文件
            else {
              File.Copy(SourceFilename, DestinationPath + filename, true);          }
           }
       }
      watch.Stop();  //時間停止  MessageBox.Show("備份完成 耗時"+watch.Elapsed+""); //顯示所消耗的時間
    }
    以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助