C# 拷贝文件夹(包含里面的所有文件)
思路:分2步:
1. 如果destDir不存在,创建它。
2. 遍历sourceDir里的所有文件,把所有文件都复制到destDir
/// <summary>
/// Copy one folder to a new folder. if destDir is not exists, then create it.
/// </summary>
/// <param name="sourceDir"></param>
/// <param name="destDir"></param>
private static void CopyFolder(string sourceDir, string destDir)
{
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
try
{
string[] fileList = Directory.GetFiles(sourceDir, "*");
foreach (string f in fileList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(destDir, fName), true);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
throw new DirectoryNotFoundException(dirNotFound.Message);
}
}