递归搜索根文件夹中的文件时,请参阅当前文件夹
本文关键字:请参阅 文件夹 文件 搜索 根文件夹 递归 | 更新日期: 2023-09-27 17:56:24
我正在使用它来选择一个根文件夹并从每个目录中获取最新文件,然后再将该文件添加到我的listbox
中,我想知道是否有办法知道当前目录以便在我仍在搜索文件时更新我的 UI。
var rootDirFile = Directory
.EnumerateFiles(pathToSearch, "*.pcap", SearchOption.TopDirectoryOnly)
.OrderByDescending(f => File.GetCreationTime(f))
.Take(1);
var allNewestFilesOfEachFolder = Directory
.EnumerateDirectories(pathToSearch, "*.*", SearchOption.AllDirectories)
.Select(d => Directory.EnumerateFiles(d, "*.pcap")
.OrderByDescending(f => File.GetCreationTime(f))
.FirstOrDefault());
foreach (string tempFile in rootDirFile.Concat(allNewestFilesOfEachFolder))
{
//add the file
}
最简单的方法是通过 BackgroundWorker 调用代码,并将 WorkerSupportsProgress
属性设置为 true
,然后处理 ReportProgress
事件
我希望下面的代码有助于解决您的问题
// Observable collection is the best choice to bind to the UI elements it automatically refreshes the changes in the UT whenever the data modifies.
ObservableCollection<string> objList = new ObservableCollection<string>();
//Bind this ObservableCollection to the UI Element with TwoWay binding
var rootDirFile = Directory.EnumerateFiles(pathToSearch, "*.pcap", SearchOption.TopDirectoryOnly).OrderByDescending(f => File.GetCreationTime(f)).Take(1);
// add to the observable collection
var allNewestFilesOfEachFolder = Directory
.EnumerateDirectories(pathToSearch, "*.*", SearchOption.AllDirectories);
// Instead of Iterating the Directory in a single time, seperate the task and iterate folder by folder basis.
foreach (string obj in allNewestFilesOfEachFolder )
{
var dir = Directory
.EnumerateFiles(obj, "*.pcap", SearchOption.TopDirectoryOnly)
.OrderByDescending(f => File.GetCreationTime(f))
.Take(1);
// add to the observable collection , it will automatically reflects the changes in the UI
}
如果您还需要绑定代码,请告诉我。我将简要解释