C#文件搜索
效果如图,可以选择是否寻找子目录
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; // C#实现文件搜索 // 作者博客 http://luyugao.com namespace test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Thread t; string lisi = ""; private delegate void SetObject(); private void button1_Click_1(object sender, EventArgs e) { FolderBrowserDialog pfd = new FolderBrowserDialog(); if (lisi != "") pfd.SelectedPath = lisi; if (pfd.ShowDialog() == DialogResult.OK) { tb_lj.Text = pfd.SelectedPath; //搜索的目录 lisi = pfd.SelectedPath;//记录上一次打开的目录 if (tb_leixing.Text.Trim().Contains("*.") && tb_leixing.Text.Trim().Length > 2) { CheckForIllegalCrossThreadCalls = false; listView1.Items.Clear(); count = 0; t = new Thread(SS); t.Start(); } else MessageBox.Show("类型不正确、形如:*.mp3"); } } private void SS() { this.Invoke(new SetObject(delegate { pic_load.Visible = true; button1.Enabled = false; })); listView1.BeginUpdate(); SearchFiles(tb_lj.Text,tb_leixing.Text.Trim());//调用查找文件函数 listView1.EndUpdate(); this.Invoke(new SetObject(delegate { pic_load.Visible = false; button1.Enabled = true; })); //MessageBox.Show("共找到文件 "+count.ToString()+" 个"); t.Abort(); } int count = 0;//记录总数 /// <summary> /// 搜索文件子程序 /// </summary> /// <param name="fpath">目录</param> /// <param name="filetype">文件类型</param> private void SearchFiles(string fpath, string filetype) { //路径、类型如:*.mp3 if (Directory.Exists(fpath)) { try { foreach (string f in Directory.GetFiles(fpath, filetype)) { //f表示完整路径的文件 string filename = Path.GetFileName(f); ListViewItem li = new ListViewItem(); count++; li.Text = count.ToString(); li.SubItems.Add(fpath); li.SubItems.Add(Getfilename(f)); listView1.Items.Add(li); } if (checkBox1.Checked)//搜索子目录 { foreach (string f in Directory.GetDirectories(fpath)) { SearchFiles(f, filetype); } } } catch (Exception er) { //MessageBox.Show(er.Message); //pic_load.Visible = false; //button1.Enabled = true; } } } private string Getfilename(string p)//获取文件名 { return p.Substring(p.LastIndexOf("\\")+1); } } }
调试环境:VS2010+.net4.0