我正在尝试创建一个程序来将文件从特定文件夹备份到主文件夹子文件夹中的文件到另一个备份文件夹。
这是我试图完成目标的代码的一部分,但是我只备份了主文件夹中的文件,并且子文件夹被完全复制(其中包含所有文件)。
public static string[] Backup(string sourceDirectory, string targetDirectory, string backupDirectory)
{
DirectoryInfo diBackup = new DirectoryInfo(backupDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
List<string> dups = new List<string>();
string[] fileNamesSource = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories);
string[] fileNamesDest = Directory.GetFiles(targetDirectory, "*", SearchOption.AllDirectories);
List<string> dupNS = new List<string>();
List<string> dupND = new List<string>();
List<string> BCKP = new List<string>();
string replacement = "";
for (int i = 0; i < fileNamesDest.Length; i++)
{
string res = fileNamesDest[i].Replace(targetDirectory, replacement);
dupND.Add(res);
}
foreach (var ns in fileNamesSource)
{
string res = ns.Replace(sourceDirectory, replacement);
dupNS.Add(res);
}
var duplicates = dupND.Intersect(dupNS);
string[] DuplicatesStringArray = duplicates.ToArray();
foreach (var dup in DuplicatesStringArray)
{
string res = targetDirectory + dup;
BCKP.Add(res);
}
string[] ToBeBackedUp = BCKP.ToArray();
Directory.CreateDirectory(diBackup.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in diTarget.GetFiles())
{
if (ToBeBackedUp.Contains(fi.FullName)){
fi.CopyTo(Path.Combine(diBackup.FullName, fi.Name), true);
}
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in diTarget.GetDirectories())
{
if (ToBeBackedUp.Contains(diSourceSubDir.FullName)) {
DirectoryInfo nextTargetSubDir =
diBackup.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
return ToBeBackedUp;
}
有关如何仅复制“source”文件夹中存在的子文件夹中的文件的任何想法?
还有CopyAll功能:
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
提前致谢。
答案 0 :(得分:1)
一个简单的解决方案:在CopyAll
方法中,将SearchOption.AllDirectories
参数加载到GetFiles
方法中:
foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories))
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
答案 1 :(得分:1)
你可以这样试试 更容易
devtools::install_github("moj-analytical-services/xltabr")
答案 2 :(得分:0)
您可以使用Directory.GetFiles
和SearchOption.AllDirectories
同时从子文件夹中提取文件:
Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)