一個拷貝整個文件夾(包括子文件夾)的方法(原創)
2024-07-21 02:16:02
供稿:網友
 
注冊會員,創建你的web開發資料庫,
需要引用命名空間:
using system.io;
/// <summary>
  /// 拷貝文件夾(包括子文件夾)到指定文件夾下,源文件夾和目標文件夾均需絕對路徑. 格式: copyfolder(源文件夾,目標文件夾);
  /// </summary>
  /// <param name="strfrompath"></param>
  /// <param name="strtopath"></param>
  //--------------------------------------------------
  //作者:kgdiwss qq:305725744
 //---------------------------------------------------
  public static void copyfolder(string strfrompath,string strtopath)
  {
   //如果源文件夾不存在,則創建
   if (!directory.exists(strfrompath))
   {    
    directory.createdirectory(strfrompath);
   }   
   //取得要拷貝的文件夾名
   string strfoldername = strfrompath.substring(strfrompath.lastindexof("http://") + 1,strfrompath.length - strfrompath.lastindexof("http://") - 1);   
   //如果目標文件夾中沒有源文件夾則在目標文件夾中創建源文件夾
   if (!directory.exists(strtopath + "http://" + strfoldername))
   {    
    directory.createdirectory(strtopath + "http://" + strfoldername);
   }
   //創建數組保存源文件夾下的文件名
   string[] strfiles = directory.getfiles(strfrompath);
   //循環拷貝文件
   for(int i = 0;i < strfiles.length;i++)
   {
    //取得拷貝的文件名,只取文件名,地址截掉。
    string strfilename = strfiles[i].substring(strfiles[i].lastindexof("http://") + 1,strfiles[i].length - strfiles[i].lastindexof("http://") - 1);
    //開始拷貝文件,true表示覆蓋同名文件
    file.copy(strfiles[i],strtopath + "http://" + strfoldername + "http://" + strfilename,true);
   }
  
   //創建directoryinfo實例
   directoryinfo dirinfo = new directoryinfo(strfrompath);
   //取得源文件夾下的所有子文件夾名稱
   directoryinfo[] zipath = dirinfo.getdirectories();
   for (int j = 0;j < zipath.length;j++)
   {
    //獲取所有子文件夾名
    string strzipath = strfrompath + "http://" + zipath[j].tostring();   
    //把得到的子文件夾當成新的源文件夾,從頭開始新一輪的拷貝
    copyfolder(strzipath,strtopath + "http://" + strfoldername);
   }
  }