首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用SymmetricDifference比较两个文件夹中是否有不相同的文件?

用SymmetricDifference比较两个文件夹中是否有不相同的文件?
EN

Stack Overflow用户
提问于 2010-12-11 15:13:38
回答 1查看 4.4K关注 0票数 0

我有两个文件夹A和B..inside,这两个文件夹有很多文件夹和文件。我正在比较这两个文件夹中具有对称差异的不同文件,并将名称和目录名写入一个文本文件中...我使用了以下代码

代码语言:javascript
复制
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); 

我需要的是,如果长度不同,我必须写入长度与目录名,如果名称不同,我必须写入名称与目录名,或如果上次写入时间不同,我必须写入最后写入时间与目录name...Any建议??

格式如下:

代码语言:javascript
复制
Missed Files detail :
---------------------
File Name           Size         Date       Path    


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

Size                 Path


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

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-11 16:16:22

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

存在于一个目录中但不存在于另一个目录中的对称difference)

  • Files文件(因此,如果它们存在于两个目录中,则使用
  • ,但是:

代码语言:javascript
复制
- Those which differ by length
- Those which differ by last write time

我会把它们分开处理。您已经知道如何完成第一部分。要获得第二部分,您需要两组文件名的交集(只需使用Intersect扩展方法)。从中你可以列出不同之处:

代码语言:javascript
复制
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 };

..。然后,您可以将它们打印出来。然后,您可以对上次写入时间执行相同的操作。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4415674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档