简体   繁体   中英

Is there a way to fetch all directories and files matching a pattern with wildcards recursively in C#?

I am looking for a library that allows me to take something similar to this:

./*
./*/*.*
./**
./**/*.*
./*.cs
./folder1/*.png

Then i would need to pass it to a method which scans the filesystem and returns these paths:

C:\folder1, C:\folder2, C:\folder3
C:\folder1\file.cs,C:\folder1\test.dll,[...], C:\folder2\image.png, [...]
C:\folder1, C:\folder1\results, C:\folder2, [...]
C:\file1.cs, C:\file2.cs, C:\file3.cs
C:\folder1\image1.png, C:\folder1\image2.png, [...]

I am aware that Directory.GetFiles() and Directory.GetDirectories exist and that they accept a filter, but i need one method that does this recursively and flexibly and returns a set of absolute paths.

One option is to use a library like Glob library which unlike .net file globbing does folders with wild cards.

var folder = @"Your path goes here";

string[] folderPatterns = { "**/bin", "**/obj" };
string[] filePatterns = { "**/*cs"};

var results = new List<string>();

foreach (var pattern in folderPatterns)
{
    results.AddRange(Glob.Directories(folder, pattern).ToArray());
}

foreach (var pattern in filePatterns)
{
    results.AddRange(Glob.Files(folder, pattern).ToArray());
}

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