Skip to content

[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);
     }         
 }

[amazon_link asins=’B01LW72R2M,B00P8VZ8T4,B015316YQE’ template=’CopyOf-ProductGrid’ store=’boyd-23′ marketplace=’CN’ link_id=”]

0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x