復(fù)制文件夾所有內(nèi)容和刪除整個(gè)文件夾的2個(gè)函數(shù)
2024-07-21 02:16:11
供稿:網(wǎng)友
 
國內(nèi)最大的酷站演示中心!
  // ======================================================
  // 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容copy到目標(biāo)文件夾下面
  // 如果目標(biāo)文件夾為只讀屬性就會(huì)報(bào)錯(cuò)。
  // april 18april2005 in stu
  // ======================================================
  public static void copydir(string srcpath,string aimpath)
  {
   try
   {
    // 檢查目標(biāo)目錄是否以目錄分割字符結(jié)束如果不是則添加之
    if(aimpath[aimpath.length-1] != path.directoryseparatorchar) 
     aimpath += path.directoryseparatorchar;
    // 判斷目標(biāo)目錄是否存在如果不存在則新建之
    if(!directory.exists(aimpath)) directory.createdirectory(aimpath);
    // 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
    // 如果你指向copy目標(biāo)文件下面的文件而不包含目錄請(qǐng)使用下面的方法
    // string[] filelist = directory.getfiles(srcpath);
    string[] filelist = directory.getfilesystementries(srcpath);
    // 遍歷所有的文件和目錄
    foreach(string file in filelist)
    {
     // 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸copy該目錄下面的文件
     if(directory.exists(file))
      copydir(file,aimpath+path.getfilename(file));
      // 否則直接copy文件
     else
      file.copy(file,aimpath+path.getfilename(file),true);
    }
   }
   catch (exception e)
   {
    messagebox.show (e.tostring());
   }
  } 
  // ======================================================
  // 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容detele
  // 測試的時(shí)候要小心操作,刪除之后無法恢復(fù)。
  // april 18april2005 in stu
  // ======================================================
  public static void deletedir(string aimpath)
  {
   try
   {
    // 檢查目標(biāo)目錄是否以目錄分割字符結(jié)束如果不是則添加之
    if(aimpath[aimpath.length-1] != path.directoryseparatorchar) 
     aimpath += path.directoryseparatorchar;
    // 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
    // 如果你指向delete目標(biāo)文件下面的文件而不包含目錄請(qǐng)使用下面的方法
    // string[] filelist = directory.getfiles(aimpath);
    string[] filelist = directory.getfilesystementries(aimpath);
    // 遍歷所有的文件和目錄
    foreach(string file in filelist)
    {
     // 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸delete該目錄下面的文件
     if(directory.exists(file))
     {
      deletedir(aimpath+path.getfilename(file));
     }
      // 否則直接delete文件
     else
     {
      file.delete (aimpath+path.getfilename(file));
     }
    }
    //刪除文件夾
    system.io .directory .delete (aimpath,true);
   }
   catch (exception e)
   {
    messagebox.show (e.tostring());
   }
  }