2

我有两个文件目录,我想确保两者是相同的。因此,我创建了一个查询以将所有文件放入 FileInfo 数组中。我按文件名对所有文件进行了分组,现在想为每个组比较文件的“LastWriteAccess”和“长度”。

但是,老实说,就像我这样做,它的速度很慢。知道如何通过 Linq 比较组内的文件的长度,如果不同,让我做“某事”吗?

...

FileInfo[] fiArrOri5 = d5ori.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly);
FileInfo[] fiArrNew5 = d5new.GetFiles("*.*", System.IO.SearchOption.TopDirectoryOnly);

FileInfo[] AllResults = new FileInfo[fiArrNew5.Length+fiArrOri5.Length];
fiArrNew5.CopyTo(AllResults, 0);
fiArrOri5.CopyTo(AllResults, fiArrNew5.Length);

var duplicateGroups = AllResults.GroupBy(file => file.Name);

        foreach (var group in duplicateGroups)
        {
            AnzahlElemente = group.Count();

            if (AnzahlElemente == 2)
            {
                if (group.ElementAt(0).Length != group.ElementAt(1).Length)
                {
                    // do sth
                }
            }

            ...
        }

编辑:

如果我只运行以下代码段,它会运行得非常快。(~00:00:00:0005156)

Console.WriteLine(group.ElementAt(0).LastWriteTime);

如果我只运行以下代码段,它会运行得非常慢。(~00:00:00:0750000)

Console.WriteLine(group.ElementAt(1).LastWriteTime);

任何想法为什么?

4

1 回答 1

1

我不确定这会更快 - 但这就是我这样做的方式:

var folderPathOne = "FolderPath1";
var folderPathTwo = "FolderPath2";

//Get all the filenames from dir 1
var directoryOne = Directory
    .EnumerateFiles(folderPathOne, "*.*", SearchOption.TopDirectoryOnly)
    .Select(Path.GetFileName);

//Get all the filenames from dir 2
var directoryTwo = Directory
    .EnumerateFiles(folderPathTwo, "*.*", SearchOption.TopDirectoryOnly)
    .Select(Path.GetFileName);

//Get only the files that appear in both directories
var filesToCheck = directoryOne.Intersect(directoryTwo);

var differentFiles = filesToCheck.Where(f => new FileInfo(folderPathOne + f).Length != new FileInfo(folderPathTwo + f).Length);

foreach(var differentFile in differentFiles)
{
    //Do something
}
于 2012-05-02T11:14:23.220 回答