How to collect all files in a Folder and its Subfolders that match a string

后端 未结 6 1017
野性不改
野性不改 2020-12-16 12:05

In C# how can I search through a Folder and its Subfolders to find files that match a string value. My string value could be \"ABC123\" and a matching file might be ABC123_

相关标签:
6条回答
  • 2020-12-16 12:50

    If the matching requirements are simple, try:

    string[] matchingFiles = System.IO.Directory.GetFiles( path, "*ABC123*" );
    

    If they require something more complicated, you can use regular expressions (and LINQ):

    string[] allFiles = System.IO.Directory.GetFiles( path, "*" );
    RegEx rule = new RegEx( "ABC[0-9]{3}" );
    string[] matchingFiles = allFiles.Where( fn => rule.Match( fn ).Success )
                                     .ToArray();
    
    0 讨论(0)
  • 2020-12-16 12:54

    You're looking for the Directory.GetFiles method:

    Directory.GetFiles(path, "*" + search + "*", SearchOption.AllDirectories)
    
    0 讨论(0)
  • 2020-12-16 12:54
     DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
     FileInfo[] rgFiles = di.GetFiles("*.aspx");
    

    you can pass in a second parameter for options. Also, you can use linq to filter the results even further.

    check here for MSDN documentation

    0 讨论(0)
  • 2020-12-16 12:54

    From memory so may need tweaking

    class Test
    {
      ArrayList matches = new ArrayList();
      void Start()
      {
        string dir = @"C:\";
        string pattern = "ABC";
        FindFiles(dir, pattern);
      }
    
      void FindFiles(string path, string pattern)
      {
        foreach(string file in Directory.GetFiles(path))
        {
          if( file.Contains(pattern) )
          {
            matches.Add(file);
          }
        }
        foreach(string directory in Directory.GetDirectories(path))
        {
          FindFiles(directory, pattern);
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-16 13:07

    Adding to SLaks answer, in order to use the Directory.GetFiles method, be sure to use the System.IO namespace.

    0 讨论(0)
  • 2020-12-16 13:10
    void DirSearch(string sDir) 
            {
                try 
                {
                    foreach (string d in Directory.GetDirectories(sDir)) 
                    {
                        foreach (string f in Directory.GetFiles(d, sMatch)) 
                        {
                              lstFilesFound.Add(f);
                        }
                        DirSearch(d);
                    }
                }
                catch (System.Exception excpt) 
                {
                    Console.WriteLine(excpt.Message);
                }
    

    where sMatch is the criteria of what to search for.

    0 讨论(0)
提交回复
热议问题