C#把一個資料夾的複製到另一個資料夾當中
public static class Test
{
public static void CopyDir(string srcPath, string aimPath)
{
try
{
// 檢查目標目錄是否以目錄分割字元結束如果不是則新增
if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
aimPath += System.IO.Path.DirectorySeparatorChar;
}
// 判斷目標目錄是否存在如果不存在則新建
if (!System.IO.Directory.Exists(aimPath))
{
System.IO.Directory.CreateDirectory(aimPath);
}
// 得到源目錄的檔案列表,該裡面是包含檔案以及目錄路徑的一個數組
// 如果你指向copy目標檔案下面的檔案而不包含目錄請使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
// 遍歷所有的檔案和目錄
foreach (string file in fileList)
{
// 先當作目錄處理如果存在這個目錄就遞迴Copy該目錄下面的檔案
if (System.IO.Directory.Exists(file))
{
CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
}
// 否則直接Copy檔案
else
{
System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
}
}
}
catch (Exception e)
{
throw;
}
}
}