我想在 C# 中将目录的全部内容从一个位置复制到另一个位置。
似乎没有办法在没有大量递归的情况下使用 System.IO
类来执行此操作。
如果我们添加对 Microsoft.VisualBasic
的引用,我们可以使用 VB 中的一种方法:
new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
这似乎是一个相当丑陋的 hack。有没有更好的办法?
最佳答案
简单多了
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}
关于c# - 在 C# 中复制目录的全部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58744/