以下比较两个文件夹并删除两个文件夹中存在的文件。
var common = from f1 in Directory.EnumerateFiles(targetDir, "*.*", SearchOption.AllDirectories)
join f2 in Directory.EnumerateFiles(sourceDir, "*.*", SearchOption.AllDirectories)
on Path.GetFileName(f1) equals Path.GetFileName(f2)
select f1;
foreach (string file in common)
{
File.Delete(file);
}
如何修改此项以删除我的targetDir中存在的源文件中不存在的文件?
答案 0 :(得分:1)
这样的事情应该这样做(仔细测试......):
// List files
var sourceFiles = Directory.EnumerateFiles(sourceDir, ".", SearchOption.AllDirectories)
var targetFiles = Directory.EnumerateFiles(targetDir, ".", SearchOption.AllDirectories)
// Makes path relatives so you can compare files in subdirectories
sourceFiles = sourceFiles .Select(f => new Uri(f).MakeRelativeUri(sourceDir))
targetFiles = targetFiles.Select(f => new Uri(f).MakeRelativeUri(targetDir))
// Get files from targetDir that does not exist in sourceDir
var filesToDelete = targetFiles.Except(sourceFiles);
foreach (string file in filesToDelete)
{
System.IO.File.Delete(System.IO.Path.Combine(targetDir, file);
}
答案 1 :(得分:0)
这是怎么回事:
list1.Where(f1 => list2.Where(f2 => f2.Name == f1.Name).Any());
我不确定你的意思是“不一样”,而是将f2.Name == f1.Name
替换为你想要的实际比较
答案 2 :(得分:0)
您可以使用
var targetFiles = Directory.GetFiles(targetDir, "*", SearchOption.AllDirectories);
var notExists = targetFiles.Where(p => !File.Exists(p.Replace(targetDir, sourceDir))).ToList();
foreach (var p in notExists) {
try {
File.Delete(p);
}
catch (Exception) {
}
}