一个拷贝整个文件夹(包括子文件夹)的方法(原创)

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 kgdiwss 的 blog

需要引用命名空间:
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("\\") + 1,strfrompath.length - strfrompath.lastindexof("\\") - 1);   

   //如果目标文件夹中没有源文件夹则在目标文件夹中创建源文件夹
   if (!directory.exists(strtopath + "\\" + strfoldername))
   {    
    directory.createdirectory(strtopath + "\\" + strfoldername);
   }
   //创建数组保存源文件夹下的文件名
   string[] strfiles = directory.getfiles(strfrompath);

   //循环拷贝文件
   for(int i = 0;i < strfiles.length;i++)
   {
    //取得拷贝的文件名,只取文件名,地址截掉。
    string strfilename = strfiles[i].substring(strfiles[i].lastindexof("\\") + 1,strfiles[i].length - strfiles[i].lastindexof("\\") - 1);
    //开始拷贝文件,true表示覆盖同名文件
    file.copy(strfiles[i],strtopath + "\\" + strfoldername + "\\" + strfilename,true);
   }
  
   //创建directoryinfo实例
   directoryinfo dirinfo = new directoryinfo(strfrompath);
   //取得源文件夹下的所有子文件夹名称
   directoryinfo[] zipath = dirinfo.getdirectories();
   for (int j = 0;j < zipath.length;j++)
   {
    //获取所有子文件夹名
    string strzipath = strfrompath + "\\" + zipath[j].tostring();   
    //把得到的子文件夹当成新的源文件夹,从头开始新一轮的拷贝
    copyfolder(strzipath,strtopath + "\\" + strfoldername);
   }
  }

本文关键:一个拷贝整个文件夹(包括子文件夹)的方法(原创)
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top