C#如何快速统计文件夹及其子文件下的文件个数?使用如下代码进行统计,发现性能不好,比较慢,特别是我文件很多时,比较慢。但右键文件夹→属性,操作系统自己的统计就非常快。我一个文件夹有369,369 个文件,这段代码运行了9分钟,但系统的属性约2分钟就统计出来了。各位大神,有没好的统计代码?  int fileNum = 0;
        /// <summary>
        /// 获取某目录下的所有文件(包括子目录下文件)的数量
        /// </summary>
        /// <param name="srcPath"></param>
        /// <returns></returns>
        public int GetFileNum(string srcPath)
        {
            try
            {              
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);               
                foreach (string file in fileList)
                {
                    if (System.IO.Directory.Exists(file))
                        GetFileNum(file);
                    else
                        fileNum++;
                }            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return fileNum;
        }c#统计文件个数

解决方案 »

  1.   

    网摘文档标题:巨快的速度求得某一个目录的大小  作者: 深度论坛关 键 字:CreateObject,Scripting.FileSystemObject,GetFolder,OLE,取得目录的大小,comobj.hpp本文转自 C++Builder 研究 - http://www.ccrun.com/article/go.asp?i=489&d=11i1qt
    在深度论坛看到的。经ccrun试验成功。用Scripting Runtime
    //------------------------------------------------------------#include "comobj.hpp"Variant fs, folder;
    Function GetFolder("GetFolder");
    PropertyGet GetSize("size");fs = Variant::CreateObject("Scripting.FileSystemObject");
    folder = fs.Exec(GetFolder << "D:\\Winnt");
    ShowMessage(folder.Exec(GetSize));
      

  2.   

    首先,不建议使用路径来判断,建议使用路径+文件名。
    /// <summary>
            /// 
            /// </summary>
            /// <param name="FileMapPath"></param>
            /// <param name="FileNum"></param>
            /// <returns></returns>
            public int GetFileNum(String FileMapPath, String FileNum)
            {
                try
                {
                    if (System.IO.File.Exists(System.Web.HttpContext.Current.Request.MapPath(FileMapPath) + FileNum))
    //先判断文件是否存在
                    {
                        return System.IO.Directory.GetFileSystemEntries(System.Web.HttpContext.Current.Request.MapPath(FileMapPath) + FileNum).Length;
    直接返回 列表的长度
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch { return 0; }
            }
    个人拙见
      

  3.   


            int count = 0;
            public void GetFilesCount(string path)
            {
                //如果嵌套文件夹很多,可以开子线程去统计
                count += System.IO.Directory.GetFiles(path).Length;
                foreach (var folder in System.IO.Directory.GetDirectories(path))
                {
                    count += GetFilesCount(folder);
                }            
            }
      

  4.   

    多线程能快点。因为你这里没啥计算,但是需要频繁调用硬盘IO。单线程情况下,你的方法需要等到硬盘IO回复才会执行下一条。而硬盘本身是有缓存的,还有潜力可挖。.net可以调用c++的dll 见 msdn: importdll
      

  5.   

    获益良多,不过用dll好像还是有点难