快速FileSize与Linq比较

时间:2012-05-02 09:09:07

标签: c# linq compare fileinfo

我有两个文件目录,我想确保两者都相同。因此我创建了一个查询,将所有文件放入FileInfo数组。我按照他们的FileName对所有文件进行了分组,现在想要比较每个组的文件“LastWriteAccess”和“Length”。

但是,说实话,就像我这样做,它的速度很慢。任何想法如何我可以比较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);

任何想法为什么?

1 个答案:

答案 0 :(得分: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
}