How can recursively search directories with multiple wildcards?

前端 未结 3 609
栀梦
栀梦 2021-01-22 00:12

Using C# (.NET), how can I search a file system given a directory search mask like this: (?)

\\\\server\\Scanner\\images\\*Images\\*\\*_*

For e

3条回答
  •  一生所求
    2021-01-22 00:42

    Edit: Ahh, new functionality with .NET 4 so you don't have to do a recursive function (Thanks Matthew Brubaker)

    IEnumerable matchingFilePaths2 = System.IO.Directory.EnumerateFiles(@"C:\some folder to start in", filePatternToMatchOn, System.IO.SearchOption.AllDirectories);
    




    First Answer:

    //get all files that have an underscore - searches all folders under the start folder
    List matchingFilePaths = new List();
    String filePatternToMatchOn = "*_*";
    FileUtilities.GetAllFilesMatchingPattern(@"C:\some folder to start in", ref matchingFilePaths, filePatternToMatchOn);
    

    ...

    public static void GetAllFilesMatchingPattern(String pathToGetFilesIn, ref List fullFilePaths, String searchPattern)
    {
        //get all files in current directory that match the pattern
        String[] filePathsInCurrentDir = Directory.GetFiles(pathToGetFilesIn, searchPattern);
        foreach (String fullPath in filePathsInCurrentDir)
        {
            fullFilePaths.Add(fullPath);
        }
    
        //call this method recursively for all directories
        String[] directories = Directory.GetDirectories(pathToGetFilesIn);
        foreach (String path in directories)
        {
            GetAllFilesMatchingPattern(path, ref fullFilePaths, searchPattern);
        }
    }
    

提交回复
热议问题