使用C#和ASP.NET将文件夹内容递归复制到另一个文件夹的最佳方式是什么?
发布于 2009-03-09 18:43:11
嗯,你可以试试这个
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
}
}
我希望这能有所帮助:)
发布于 2009-03-09 18:43:33
只需在Microsoft.VisualBasic.dll
程序集中使用Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory
即可。
添加对Microsoft.VisualBasic
的引用
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);
发布于 2010-12-16 00:05:41
你可以使用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);
}
https://stackoverflow.com/questions/627504
复制相似问题