C# Recurse Directories using Directory.GetFiles and search pattern

前端 未结 6 1896
时光说笑
时光说笑 2021-01-21 02:42

I want to find all excel files within a directory structure using recursion. The problem is, the search pattern used in Directory.GetFiles only allows a single extension at a t

6条回答
  •  無奈伤痛
    2021-01-21 03:16

    In .NET every version there is SearchOption.TopDirectoryOnly and SearchOption.AllDirectories

    In .NET 4 you could very efficiently do e.g.:

            var regex = new Regex(@"\d+", RegexOptions.Compiled);
    
            var files = new DirectoryInfo(topdir)
    
                .EnumerateFiles("*.*", SearchOption.AllDirectories)
    
                .Where(fi => regex.IsMatch(fi.Name));
    

    (This example filters for files having two digits in the name)

    To emulate this, write a recursive enumerator method (yield return) to return all files, and filter the result like so:

     IEnumerable Recurse(string topdir)
     { 
          // for each GetFiles() array element
          //      if is_not_dir yield return
          //      else Recurse(subdir)          
     }
    
     var filtered = Recurse.Where(fi => regex.IsMatch(fi.Name));
    

    HTH

提交回复
热议问题