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

后端 未结 6 1041
野性不改
野性不改 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();
    

提交回复
热议问题