在递归搜索根文件夹内的文件时,请查看当前文件夹

时间:2013-01-29 11:44:30

标签: c# winforms

我使用它来选择一个根文件夹并从每个目录中获取最新文件,然后将这些文件添加到我的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
}

2 个答案:

答案 0 :(得分:0)

可能最容易通过BackgroundWorkerWorkerSupportsProgress属性设置为true来调用您的代码,然后处理ReportProgress事件

答案 1 :(得分:0)

我希望以下代码有助于解决您的问题

// 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            

            }

如果您还需要绑定代码,请告诉我。我将简要解释一下