获取某目录下的所有文件(包括子目录下文件)的数量(C#)

以前写过一个通过计算目录遍历所有文件和子目录的方法来获得某目录下的文件个数,结果发现速度极慢,远远不及系统本身目录属性里边显示的速度。

None.gif int  fileNum  =   0 ;
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// 获取某目录下的所有文件(包括子目录下文件)的数量
InBlock.gif
/// </summary>
InBlock.gif
/// <param name="srcPath"></param>
ExpandedBlockEnd.gif
/// <returns></returns>

None.gif public   int  GetFileNum( string  srcPath)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
try
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
InBlock.gif
        string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
InBlock.gif        
// 遍历所有的文件和目录
InBlock.gif
        foreach(string file in fileList)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// 先当作目录处理如果存在这个目录就重新调用GetFileNum(string srcPath)
InBlock.gif
            if(System.IO.Directory.Exists(file))
InBlock.gif                GetFileNum(file);
InBlock.gif            
else
InBlock.gif                fileNum
++;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockEnd.gif    }

InBlock.gif    
catch (Exception e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        MessageBox.Show (e.ToString());
ExpandedSubBlockEnd.gif    }

InBlock.gif    
return fileNum;
ExpandedBlockEnd.gif}

近来发现了一个效率更高的方法,只需遍历目录就能获得文件个数,现分享一下
None.gif System.IO.DirectoryInfo dirInfo  =   new  System.IO.DirectoryInfo(dirPath);  
None.gif
None.gif
public   static   int  GetFilesCount(System.IO.DirectoryInfo dirInfo) 
ExpandedBlockStart.gifContractedBlock.gif
dot.gif
InBlock.gif    
int totalFile = 0
InBlock.gif    totalFile 
+= dirInfo.GetFiles().Length; 
InBlock.gif    
foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories()) 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif
InBlock.gif        totalFile 
+= GetFilesCount(subdir); 
ExpandedSubBlockEnd.gif    }
 
InBlock.gif    
return totalFile; 
ExpandedBlockEnd.gif}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值