简体   繁体   中英

How can recursively search directories with multiple wildcards?

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

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

For example, I need to first find all top-level directories:

\\server\Scanner\images\Job1Images
\\server\Scanner\images\Job2Images

...then I need to procede further with the search mask:

\\server\Scanner\images\Job1Images\*\*_*
\\server\Scanner\images\Job2Images\*\*_*

This doesn't seem too complicated but I can't figure it out for the life of me...

As mentioned above, I'm using C# and .NET. The search can be trying to locate directories or files. (ie *.txt, or <*Directory>)

Like this:

Top Level Directories:

  //get Top level
   string[] TopLevel = Directory.GetDirectories(path);

And then you will have to do a resursive function of this folders using wildcard pattern, for example:

 // Only get subdirectories that begin with the letter "p." 
            string pattern = "p*";
            string[] dirs = folder.GetDirectories(path, pattern);

I suggest you play with wildcards to get the array output and you will figure out which is the best way, if using resursive function or directly quering paths.

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

IEnumerable<String> 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<String> matchingFilePaths = new List<string>();
String filePatternToMatchOn = "*_*";
FileUtilities.GetAllFilesMatchingPattern(@"C:\some folder to start in", ref matchingFilePaths, filePatternToMatchOn);

...

public static void GetAllFilesMatchingPattern(String pathToGetFilesIn, ref List<String> 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);
    }
}
    public static IEnumerable<string> GetImages()
{    
    //For each "*Image" directory
    foreach (var jobFolder in Directory.EnumerateDirectories(@"\\server\Scanner\images", "*Images"))
    {
        //For each first level subdirectory
        foreach (var jobSubFolder in Directory.EnumerateDirectories(jobFolder))
        {
            //Enumerate each file containing a '_'
            foreach (var filePath in Directory.EnumerateFiles(jobSubFolder, "*_*", SearchOption.TopDirectoryOnly))
            {                               
                yield return filePath;
            }
        }
    }
}

Only the files from the first level subdirectories of each "*Image" directory are enumerated.

Finally you can use it with:

foreach (var path in GetImages())
            {
                Console.WriteLine(path);
            }

There is a C# procedure where you can search folder by path pattern with wildcards like * and ?.

Example if path pattern C:\\Folder?*\\Folder2 is passed to the procedru, then a list of folder path will be returned

C:\\Folder1\\A\\Folder2

C:\\FolderA\\B\\Folder2

...

and so on

static List<string> GetFoldersByPathPattern(string folderPathPattern)
{
    List<string> directories = new List<string>();
    directories.Add("");

    string[] folderParts = folderPathPattern.Split(new char[] { '\\' }, StringSplitOptions.None);
    foreach (string folderPart in folderParts)
    {

        if (folderPart.Contains('*') || folderPart.Contains('?'))
        {
            List<string> newDirectories = new List<string>();

            foreach (string directory in directories)
            {
                foreach (string newDirectory in Directory.GetDirectories(directory, folderPart))
                {
                    newDirectories.Add(newDirectory);
                }
            }

            directories = newDirectories;
        }
        else
        {
            for (int i = 0; i < directories.Count(); i++)
            {
                directories[i] = directories[i] + folderPart + "\\";
            }
        }
    }

    return directories;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM