Recursively walking through a directory tree and listing file names

后端 未结 2 865
孤城傲影
孤城傲影 2021-01-02 10:03

I\'m trying to walk through a whole directory tree and print out all the file names on a listbox control. I wrote some code but there are errors. Not sure what I\'m doing wr

相关标签:
2条回答
  • 2021-01-02 10:36

    There is a complete example on the Microsoft support site

    The issue here is that you want to call DirSearch from the event handler, but it appears you're trying to define the method DirSearch inside the event handler. This is not valid.

    You need to change your code as follows:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        string sourcePath = @"C:\temp\";
        this.DirSearch(sourcePath);
    }
    
    private void DirSearch(string sDir) 
    {
        try 
        {
            foreach (string f in Directory.GetFiles(sDir, txtFile.Text)) 
            {
                lstFilesFound.Items.Add(f);
            }
    
            foreach (string d in Directory.GetDirectories(sDir)) 
            {
                this.DirSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            listBox1.Items.Add(ex.Message);
        }
    }
    
    0 讨论(0)
  • 2021-01-02 10:37

    Use GetDirectories() overload accepting SearchOption:

    string[] dirs = Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
    foreach(dir)
    {
        ...
    }
    

    or better EnumerateFiles():

    IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    foreach(files)
    {
        ...
    }
    

    Notice it performs lazy filesystem scan.

    0 讨论(0)
提交回复
热议问题