多线程文件搜索Demo 【原创】

本Demo只是提供一钟思路,有兴趣的朋友可以在其基础上完善!用到了垮线程访问UI控件。
代码
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Thread t
= null;
private int btnTimes = 0;
public delegate void AddFileToListboxHandle(FileInfo fileFullName);
public event AddFileToListboxHandle addfilenameEvent;
private void AddFileToListbox(FileInfo f)
{

this.listBox1.Items.Add(f.Name);
this.label1.Text = f.FullName;
}
delegate void finishedFindFileHandle(string A);
private void FinishFindFile(string a)
{

this.label1.Text = a;
this.label1.ForeColor = Color.Red;
}
public Form1()
{
InitializeComponent();
this.addfilenameEvent += new AddFileToListboxHandle(AddFileToListbox);
}

private void button1_Click(object sender, EventArgs e)
{

string FilePath = "F:\\";
if (t == null)
{
t
= new Thread(new ParameterizedThreadStart(this.getFileName));
if (t.IsAlive == false)
{
t.Start(FilePath);
t.IsBackground
= true;
}
else
{
return;
}
}
}
private void getFileName(object b)
{
string filePath = b.ToString();
if (Directory.Exists(filePath) == true)
{

DirectoryInfo fileContext
= new DirectoryInfo(filePath);
int fileCount = fileContext.GetFileSystemInfos().Length;
if (fileCount == 0)
{
return;
}
else
{
FileSystemInfo[] fs
= fileContext.GetFileSystemInfos();
foreach (FileSystemInfo f in fs)
{

if (f is FileInfo)
{

this.listBox1.Invoke(new AddFileToListboxHandle(this.AddFileToListbox), f);
}
else if (f is DirectoryInfo)
{
getFileName(f.FullName);

}

}

}


}

}


 

posted @ 2010-06-21 00:05  来了就看看  阅读(190)  评论(0编辑  收藏  举报