C#中拷贝指定文件夹下的所有文件夹目录到指定文件夹中的方法
原文地址:http://www.biye5u.com/article/Csharp/fileprog/2011/4198.html
本文給出了一個(gè)在C#中拷貝指定文件夾下的所有文件夾目錄到指定文件夾中的方法。
public static void CopyFolder(string strFromPath,string strToPath)
{
?????? //如果源文件夾不存在,則創(chuàng)建
?????? if (!Directory.Exists(strFromPath))
?????? {?
????????????? Directory.CreateDirectory(strFromPath);
?????? }
?????? //取得要拷貝的文件夾名
?????? string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") +
???????? 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
?????? //如果目標(biāo)文件夾中沒(méi)有源文件夾則在目標(biāo)文件夾中創(chuàng)建源文件夾
?????? if (!Directory.Exists(strToPath + "\\" + strFolderName))
?????? {?
????????????? Directory.CreateDirectory(strToPath + "\\" + strFolderName);
?????? }
?????? //創(chuàng)建數(shù)組保存源文件夾下的文件名
?????? string[] strFiles = Directory.GetFiles(strFromPath);
?????? //循環(huán)拷貝文件
?????? for(int i = 0;i < strFiles.Length;i++)
?????? {
????????????? //取得拷貝的文件名,只取文件名,地址截掉。
????????????? string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
????????????? //開(kāi)始拷貝文件,true表示覆蓋同名文件
????????????? File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);
?????? }
?????? //創(chuàng)建DirectoryInfo實(shí)例
?????? DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
?????? //取得源文件夾下的所有子文件夾名稱
?????? DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
?????? for (int j = 0;j < ZiPath.Length;j++)
?????? {
????????????? //獲取所有子文件夾名
????????????? string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();?
????????????? //把得到的子文件夾當(dāng)成新的源文件夾,從頭開(kāi)始新一輪的拷貝
????????????? CopyFolder(strZiPath,strToPath + "\\" + strFolderName);
?????? }
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/gbnw/p/4585775.html
總結(jié)
以上是生活随笔為你收集整理的C#中拷贝指定文件夹下的所有文件夹目录到指定文件夹中的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2782: [HNOI2006]最短母串
- 下一篇: 深入C#类的方法