How do I iterate through a directory stopping at a folder that excludes a specific character?

119 views Asked by At

I would like to iterate through a directory and stop at the first folder that doesn't end in "@"

This is what I tried so far (based on another question from this site):

string rootPath = "D:\\Pending\\Engineering\\Parts\\3";
string targetPattern = "*@";

string fullPath = Directory
                 .EnumerateFiles(rootPath, targetPattern, SearchOption.AllDirectories)                                               
                 .FirstOrDefault();

if (fullPath != null)
    Console.WriteLine("Found " + fullPath);
else
    Console.WriteLine("Not found");

I know *@ isn't correct, no idea how to do that part.
Also I'm having problems with SearchOption Visual studio says "it's an ambiguous reference."

Eventually I want the code to get the name of this folder and use it to rename a different folder.

FINAL SOLUTION

I ended up using a combination of dasblikenlight and user3601887

string fullPath = Directory
                   .GetDirectories(rootPath, "*", System.IO.SearchOption.TopDirectoryOnly)
                   .FirstOrDefault(fn => !fn.EndsWith("@"));
2

There are 2 answers

0
Sergey Kalinichenko On BEST ANSWER

Since EnumerateFiles pattern does not support regular expressions, you need to get all directories, and do filtering on the C# side:

string fullPath = Directory
    .EnumerateFiles(rootPath, "*", SearchOption.AllDirectories)                                               
    .FirstOrDefault(fn => !fn.EndsWith("@"));
0
lezhkin11 On

Or just replace EnumerateFiles with GetDirectories

string fullPath = Directory
                 .GetDirectories(rootPath, "*@", SearchOption.AllDirectories)
                 .FirstOrDefault();