我正在尝试使用以下函数将包括所有子目录的整个目录复制到同一驱动器上的另一个文件夹:
private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it’s new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
调用:
public void copyTemplate(string templatepath, string destpath)
{
DirectoryInfo s = new DirectoryInfo(@"C:\temp\templates\template1");
DirectoryInfo t = new DirectoryInfo(@"C:\temp\www_temp\gtest");
CopyAll(s, t);
}
这会产生错误:
The process cannot access the file 'C:\temp\templates\template1\New folder\alf.txt' because it is being used by another process.
我没有使用该文件,第三方软件告诉我没有进程正在锁定该文件,所以我怀疑复制功能在某处跳闸。
任何人都可以阐明为什么会发生这种情况或建议一个可以更好地完成这项工作的功能吗?
谢谢