本文給出了一個在C#中拷貝指定文件夾下的所有文件夾目錄到指定文件夾中的方法。
/**//// <summary>
/// 拷貝文件夾(包括子文件夾)到指定文件夾下,源文件夾和目標文件夾均需絕對路徑. 格式: CopyFolder(源文件夾,目標文件夾);
/// </summary>
/// <param name="strFromPath"></param>
/// <param name="strToPath"></param>
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);
}
}
使用格式: CopyFolder(源文件夾,目標文件夾);
如果目標文件夾不存在,程序將自動創建。
新聞熱點
疑難解答