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

后端 未结 6 1036
野性不改
野性不改 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: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);
        }
      }
    }
    

提交回复
热议问题