Reputation: 2041
I need to search particular folder in directory.
I dont want to go for files, no need to search files.
I can search particular folder in directory but for I have to go for loop of files like
foreach (FileInfo f in dir.EnumerateFiles())
{
//code
}
foreach (DirectoryInfo d in dir.EnumerateDirectories())
{
Call function recursively
}
I need to search particular folder only. Because I have so many files around 20,000 , so If I use above code than loop will go all the files, and take more time.
But I need some folders only like
Regex.IsMatch(dir.FullName, @"1293.*T.*"))
How can i do that without going in files loop.
Upvotes: 1
Views: 2685
Reputation: 43636
Your question is very confusing, but do you want to get the directories that match the Regex pattern?
foreach (DirectoryInfo d in dir.EnumerateDirectories().Where(d => Regex.IsMatch(dir.FullName, @"1293.*T.*")))
{
}
Upvotes: 0
Reputation: 8469
If the search pattern provided by the overload of Directory.GetDirectory
isn't strong enough for your needs, you can use a custom method.
static string SearchDirectory(string path, string pattern)
{
var regex = new Regex(pattern);
foreach (var d in Directory.GetDirectories(path))
{
var dirName = d.Substring(d.LastIndexOf('\\') + 1);
if (regex.IsMatch(dirName)) return d;
SearchDirectory(d, pattern);
}
return null;
//Or throw an Exception
}
You might want to surround the foreach
loop in a try/catch
block.
Upvotes: 2
Reputation: 44971
You can use the System.IO.Directory.GetDirectories overload that accepts a search pattern.
For example:
string[] dirs = Directory.GetDirectories(@"c:\", "c*");
Upvotes: 1