C#遍历子目录文件

Winform界面设计:放置一个TextBox控件(命名为:txtPath),两个按钮控件(一个btnSelect,一个btnStart),一个显示文件列表Label控件(lblFileList),还有一个重要的folderBrowserDialog1控件。

1 StringBuilder strFile = new StringBuilder("文件列表:");
1 //选择文件夹

2 private void btnSelect_Click(object sender, EventArgs e)

3 {

4     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

5     {

6         txtPath.Text = folderBrowserDialog1.SelectedPath;

7     }

8 }
1 //开始搜索

2 private void btnStart_Click(object sender, EventArgs e)

3 {

4     GetFiles(txtPath.Text);

5     lblFileList.Text = strFile.ToString();

6 }
 1 //获取指定目录文件

 2 private void GetFiles(string path)

 3 {

 4     if (path.Length == 0 || !Directory.Exists(path))

 5     {

 6         MessageBox.Show("请选择文件夹!");

 7         return;

 8     }

 9     DirectoryInfo dirFolder = new DirectoryInfo(path);

10     //遍历文件夹

11     foreach (FileInfo file in dirFolder.GetFiles())

12     {

13         //如果要获取指定扩展名(比如.pdf)文件

14         if (file.Extension.IndexOf("pdf")>0)

15         {

16             strFile.Append(file.Name+"\n");

17         }

18     }

19     string[] dirs = Directory.GetDirectories(path); //获取子目录

20     foreach (string dir in dirs)

21     {

22         //递归

23         GetFiles(dir);

24     }

25 }

 

你可能感兴趣的:(C#)