1. 程式人生 > >轉載---C# 復制文件夾下的(內容)到指定文件夾中

轉載---C# 復制文件夾下的(內容)到指定文件夾中

tostring file -- hid 復制文件 html zip () div

原文地址:https://zhidao.baidu.com/question/872350189026087492.html

//
復制指定文件夾中的所有文件夾(或文件) 到指定文件夾
//遞歸方法 CopyFolder(原文件夾路徑,目標文件夾路徑)
public 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); } }


轉載---C# 復制文件夾下的(內容)到指定文件夾中