Каков наилучший способ рекурсивного копирования содержимого папки в другую папку с использованием С# и ASP.NET?
Каков наилучший способ рекурсивного копирования содержимого в С#?
Ответ 1
Ну, вы можете попробовать это
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
}
}
Надеюсь, это поможет:)
Ответ 2
Просто используйте Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory
в Microsoft.VisualBasic.dll
.
Добавьте ссылку на Microsoft.VisualBasic
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);
Ответ 3
Вы можете использовать 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);
}