var dir1Files = dir1.GetFiles("*", SearchOption.AllDirectories);
var dir2Files = dir2.GetFiles("*", SearchOption.AllDirectories);
var difference = dir1Files.ToHashSet();
difference.SymmetricExceptWith(dir2Files);
string[] foo1 = difference.Select(c => c.Name).ToArray();
File.WriteAllLines(@"d:\log1.txt", foo1);
这里我将基于名称和文本文件中的两个文件进行比较...但我需要将名称和目录名称一起写为comparing two folders for non identical files? ...
有任何建议吗?
修改 我有两个文件夹A和B ..里面有两个文件夹,有很多文件夹和文件... 我将这两个文件夹与具有对称差异的非相同文件进行比较,并将名称和目录名称写入文本文件...我的问题是对称差异工作正常,并且将两个不相同的文件名写入日志文件...但我必须用该目录名写出文件名......
此代码工作正常
var dir1Files = dir1.GetFiles("*", SearchOption.AllDirectories).Select(x => new { x.Name, x.Length });
var dir2Files = dir2.GetFiles("*", SearchOption.AllDirectories).Select(x => new { x.Name, x.Length });
var difference = dir1Files.ToHashSet();
difference.SymmetricExceptWith(dir2Files);
string[] foo1 = difference.Select(c => c.Name).ToArray();
File.WriteAllLines(@"d:\log1.txt", foo1);
这里我不能这样给予
string[] foo1 = difference.Select(c => c.Name+""+c.DirectoryName).ToArray();
答案 0 :(得分:2)
我认为最好的方法是编写自己的IEqualityComparer<FileInfo>
实现,强制执行两个文件之间的相等定义。
public class FileInfoNameLengthEqualityComparer : EqualityComparer<FileInfo>
{
public override bool Equals(FileInfo x, FileInfo y)
{
if (x == y)
return true;
if (x == null || y == null)
return false;
// 2 files are equal if their names and lengths are identical.
return x.Name == y.Name && x.Length == y.Length;
}
public override int GetHashCode(FileInfo obj)
{
return obj == null
? 0 : obj.Name.GetHashCode() ^ obj.Length.GetHashCode();
}
}
然后其余部分看起来像(未经测试):
// Construct custom equality-comparer.
var comparer = new FileInfoNameLengthEqualityComparer();
// Create sets of files from each directory.
var sets = new[] { dir1, dir2 }
.Select(d => d.GetFiles("*", SearchOption.AllDirectories))
.Select(files => new HashSet<FileInfo>(files, comparer))
.ToArray();
// Make the first set contain the set-difference as determined
// by the equality-comparer.
sets[0].SymmetricExceptWith(sets[1]);
// Project each file to its full name and write the file-names
// to the log-file.
var lines = sets[0].Select(fileInfo => fileInfo.FullName).ToArray();
File.WriteAllLines(@"d:\log1.txt", lines);