使用SymmetricDifference比较两个不同文件的文件夹?

时间:2010-12-11 07:13:38

标签: c# linq

我有两个文件夹A和B ..里面有两个文件夹,有很多文件夹和文件...我正在比较这两个文件夹是否存在对称差异的相同文件,并将名称和目录名称写入文本文件......我用过这段代码

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 && x.LastWriteTime== y.LastWriteTime;
        }

        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); 

我需要的是,如果长度不同,我必须与目录名一起写长度,如果名称不同,我必须写名字和目录名,或者如果lastwritetime不同,我必须写lastwritetime和目录名...任何建议??

采用以下格式:

Missed Files detail :
---------------------
File Name           Size         Date       Path    


Discrepancies in File Size:
--------------------------

Size                 Path


Discrepancies in File Date:
--------------------------
date                 path

1 个答案:

答案 0 :(得分:1)

我觉得你正在寻找不同的东西,真的:

  • 存在于一个目录中但不存在于另一个目录中的文件(因此使用对称差异)

  • 的文件存在于两个目录中,但随后:

    • 长度不同的那些
    • 与上次写入时间不同的那些

我会分开对待这些。你已经知道如何做第一部分了。要获得第二部分,您需要两组文件名的交集(只需使用Intersect扩展方法)。从那里你可以列出差异:

var differentLengths = from name in intersection
                       let file1 = new FileInfo(directory1, name)
                       let file2 = new FileInfo(directory2, name)
                       where file1.Length != file2.Length
                       select new { Name = name,
                                    Length1 = file1.Length,
                                    Length2 = file2.Length };

...然后你可以打印出来。然后,您可以在上次写入时间内执行相同的操作。

换句话说,您实际上并不需要一个比较所有属性的比较器。

相关问题