日期:2014-05-18  浏览次数:20841 次

高分求教C#遍历指定目录下所有文件(包括子目录中的文件)较好的办法?
最近要做一个Winform,实现指定文件夹目录后,扫描该目录下所有的文件,包括该文件夹下的子目录及孙目录中的文件
例:扫描D盘中所有文件夹里面的所有文件,有没有什么较为高效的办法,要求能防止程序卡死!不要一点击程序就出现未响应状态!
C# code

//定义代理
        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)
        {
        }


现代码如上,麻烦高手指教!

------解决方案--------------------
放到线程中,用委托和UI交互
------解决方案--------------------
其实你并不用一下子完全扫描出来。因为看的人不会一下子展开全部节点
你可以在展开某个节点的时候扫描该节点下的内容