递归遍历目录树并列出文件名 [英] Recursively walking through a directory tree and listing file names

查看:259
本文介绍了递归遍历目录树并列出文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试浏览整个目录树,并在列表框控件上打印所有文件名。我写了一些代码,但是有错误。不知道我在做什么错。顺便说一下,这是在Visual Studio中使用WPF的C#语言中。

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 wrong. By the way, this is in C# using WPF in Visual Studio.

这是Visual Studio中的整个项目解决方案: http://tinyurl.com/a2r5jv9

Here is the whole project solution in Visual Studio: http://tinyurl.com/a2r5jv9

这是MainWindow.xaml.cs中的代码不想下载项目解决方案: http://pastebin.com/cWRTeq3N

Here is the code from MainWindow.xaml.cs if you don't want to download the project solution: http://pastebin.com/cWRTeq3N

我也会在这里粘贴代码。

I'll paste the code here as well.

public partial class MainWindow : Window
{
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        string sourcePath = @"C:\temp\";            

        static void DirSearch(string sourcePath)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sourcePath))
                {
                    foreach (string f in Directory.GetFiles(d))
                    {
                        listBox1.Items.Add(f);
                    }
                    DirSearch(d);
                }
            }                      
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }
        }
    }
}


推荐答案

Microsoft支持站点上有一个完整示例

There is a complete example on the Microsoft support site

这里的问题是您想从事件处理程序中调用 DirSearch ,但是看来您正在尝试在事件处理程序中定义方法 DirSearch 。这是无效的。

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);
    }
}

这篇关于递归遍历目录树并列出文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆