[C#]单线程递归遍历文件夹

最近在做一些代码分析的小程序,抓出代码里面符合特定规则的文件,把符合特征的代码文件和代码片段抓出来,输出成一个txt文件,方便统计和查找,为日后分析做准备,因为要遍历所有项目文件,所以需要程序依次访问每个文件夹下的所有文件,因为还有子文件夹,因此想到了用递归来遍历,这个实现没有涉及多线程,以后有机会再改成多线程吧,这里记录一下方法,用到了尾递归。

 public void ScanFile(string dirpath, string extension = "*.cs", Action action)
 {
     DirectoryInfo dirInfo = new DirectoryInfo(dirpath);
     FileInfo[] files = dirInfo.GetFiles(extension);
     List infoList = new List();
     foreach (FileInfo fileInfo in files)    //遍历当前文件夹下的所有文件,并调用action
     {
         action(fileInfo);
     }

     DirectoryInfo[] info = dirInfo.GetDirectories();
     foreach (DirectoryInfo d in info)
     {
         ScanFile(dirInfo + d.ToString() + "\\", extension, action);
     }         
 }

博主为你专属推荐

博主开通了微信公众号,欢迎关注啦

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.