高分求教C#遍历指定目录下所有文件(包括子目录中的文件)较好的办法?

情傷 2012-05-25 11:14:08
最近要做一个Winform,实现指定文件夹目录后,扫描该目录下所有的文件,包括该文件夹下的子目录及孙目录中的文件
例:扫描D盘中所有文件夹里面的所有文件,有没有什么较为高效的办法,要求能防止程序卡死!不要一点击程序就出现未响应状态!

//定义代理
delegate void Mydelegate(DirectoryInfo dir, DateTime dtStart, DateTime dtEnd);
delegate void PrintDelegate(FileInfo file);

private void btnSelectDirectory_Click(object sender, EventArgs e)
{
FolderBrowserDialog path = new FolderBrowserDialog();
path.ShowDialog();
if (!"".Equals(path.SelectedPath))
{
tboSelectPath.Text = path.SelectedPath;
}
}

private void btnStartScan_Click(object sender, EventArgs e)
{
DateTime dtStart = dateTimePicker1.Value.Date;
DateTime dtEnd = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day + 1, 0, 0, 0);
DirectoryInfo di = new DirectoryInfo("F:\\bea");
Scan(di, dtStart, dtEnd);
}

private void print(FileInfo file)
{

if (tboFiles.InvokeRequired)
{
PrintDelegate Md = new PrintDelegate(print);
tboFiles.Invoke(Md, file); //
}
else
tboFiles.Text += file.FullName;
}

private void Scan(DirectoryInfo dir, DateTime dtStart, DateTime dtEnd)
{
if (dir.Exists)
{
FileInfo[] files = dir.GetFiles();
if (files.Length > 0)
{

foreach (FileInfo item in files)
{
if (item.LastWriteTime > dtStart && item.LastWriteTime < dtEnd)
{
PrintDelegate Md = new PrintDelegate(print);
//实例一个回调代理
AsyncCallback callback = new AsyncCallback(callbackMethod);
//开始执行异步方法
Md.BeginInvoke(item, callbackMethod, Md);
}
}
}
DirectoryInfo[] dirs = dir.GetDirectories();
if (dirs.Length > 0)
{
foreach (DirectoryInfo item in dirs)
{
Mydelegate Md = new Mydelegate(Scan);
//实例一个回调代理
AsyncCallback callback = new AsyncCallback(callbackMethod);
//开始执行异步方法
Md.BeginInvoke(item, dtStart, dtEnd, callbackMethod, Md);
}
}
}
}//回调方法
static void callbackMethod(IAsyncResult Ias)
{
}

现代码如上,麻烦高手指教!
...全文
182 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

25,980

社区成员

发帖
与我相关
我的任务
社区描述
高性能WEB开发
社区管理员
  • 高性能WEB开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧