gpt4 book ai didi

c# - Fast FileSize 与 Linq 比较

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:16 26 4
gpt4 key购买 nike

我有两个文件目录,我想确保两者完全相同。因此,我创建了一个查询,将所有文件放入 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);

知道为什么吗?

最佳答案

我不确定这会更快 - 但我会这样做:

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
}

关于c# - Fast FileSize 与 Linq 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10410735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com