使用C#和ASP.NET以递归方式将文件夹的内容复制到另一个文件夹的最佳方法是什么?
那么你可以试试这个
DirectoryInfo sourcedinfo = new DirectoryInfo(@"E:\source"); DirectoryInfo destinfo = new DirectoryInfo(@"E:\destination"); copy.CopyAll(sourcedinfo, destinfo);
这是完成所有工作的方法:
public void CopyAll(DirectoryInfo source, DirectoryInfo target) { try { //check if the target directory exists if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } //copy all the files into the new directory foreach (FileInfo fi in source.GetFiles()) { fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); } //copy all the sub directories using recursion foreach (DirectoryInfo diSourceDir in source.GetDirectories()) { DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name); CopyAll(diSourceDir, nextTargetDir); } //success here } catch (IOException ie) { //handle it here } }
我希望这个能帮上忙 :)
只需Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory
在Microsoft.VisualBasic.dll
装配中使用.
添加引用 Microsoft.VisualBasic
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);
您可以使用SearchOption.AllDirectories
递归搜索文件夹,只需在复制之前创建目录...
// string source, destination; - folder paths int pathLen = source.Length + 1; foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories)) { string subPath = dirPath.Substring(pathLen); string newpath = Path.Combine(destination, subPath); Directory.CreateDirectory(newpath ); } foreach (string filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories)) { string subPath = filePath.Substring(pathLen); string newpath = Path.Combine(destination, subPath); File.Copy(filePath, newpath); }