我发现this solution on MSDN可以将文件从一个目录复制到另一个目录,但它只从主目录而不是子目录复制。
如何修改此解决方案,以便复制所有文件夹及其内容?
string StartDirectory = @"C:\Users\...";
string EndDirectory = @"C:\Users\....";
//Creates all of the directories and sub-directories
foreach (string dirPath in Directory.GetDirectories(StartDirectory, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(StartDirectory, EndDirectory));
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
答案 0 :(得分:5)
扩展第一个循环以包围内部循环,它应该工作。您正在使用第一个for循环搜索所有文件夹,但仅枚举顶级文件夹中的文件。您还需要枚举每个子文件夹中的文件。此外,在这种情况下,DirectoryInfo将比Directory更容易使用。
DirectoryInfo StartDirectory = new DirectoryInfo(@"C:\Users\...");
DirectoryInfo EndDirectory = new DirectoryInfo(@"C:\Users\....");
//Creates all of the directories and sub-directories
foreach (DirectoryInfo dirInfo in StartDirectory.GetDirectories("*", SearchOption.AllDirectories))
{
string dirPath = dirInfo.FullName;
string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
Directory.CreateDirectory(outputPath);
foreach (FileInfo file in dirInfo.EnumerateFiles())
{
using (FileStream SourceStream = file.OpenRead())
{
using (FileStream DestinationStream = File.Create(outputPath + file.Name))
{
SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
答案 1 :(得分:1)
用两个循环解决它,一个用于所有子目录(第一个)和一个用于主目录:
foreach (string dirPath in Directory.GetDirectories(StartDirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(StartDirectory, EndDirectory));
foreach (string filename in Directory.EnumerateFiles(dirPath))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(filename.Replace(StartDirectory, EndDirectory)))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}