【问题标题】:See the present folder when recursive search for files inside root folder递归搜索根文件夹内的文件时查看当前文件夹
【发布时间】:2013-01-29 11:44:29
【问题描述】:

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

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    通过WorkerSupportsProgress 属性设置为trueBackgroundWorker 调用您的代码可能最简单,然后处理ReportProgress 事件

    【讨论】:

    • 我可以举个例子吗? (我是新开发者...)
    【解决方案2】:

    我希望下面的代码可以帮助您解决问题

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

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

    【讨论】:

    • 我不明白这段代码是做什么的,你能解释一下吗(我是一个新开发者)
    • 你想在哪里展示采集结果,UI组件的方式?请在 msdn 中学习 binding 和 ObservableCollection。然后,您对这篇文章有更好的了解。
    • 我想在我的标签上看到收集结果
    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2013-02-03
    相关资源
    最近更新 更多