C#中拷贝指定文件夹下的所有文件夹目录到指定文件夹中的方法
原文地址:http://www.biye5u.com/article/Csharp/fileprog/2011/4198.html
本文給出了一個在C#中拷貝指定文件夾下的所有文件夾目錄到指定文件夾中的方法。
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);
?????? }
}
?
轉載于:https://www.cnblogs.com/gbnw/p/4585775.html
總結
以上是生活随笔為你收集整理的C#中拷贝指定文件夹下的所有文件夹目录到指定文件夹中的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2782: [HNOI2006]最短母串
- 下一篇: 深入C#类的方法