0

I want to iterate folders with Directory.EnumerateDirectories and check if there are folders starting with a specific pattern in each path.

static void SearchFolder(string searchDirectory)
{
    foreach (var path in Directory.EnumerateDirectories(searchDirectory))
    {
        var pattern = folderName + @"\10.*";
        var isProjectFolderMatch = Regex.Match(path, pattern);

        if (isProjectFolderMatch.Success)
        {
            Console.WriteLine($"found: {path}");

        }
    }
}

But the regex match throws an error

'C:\Folder\10.*' - Reference to undefined group number 1.'

How can I build a dynamic pattern in this way?

Thanks!

mottosson
  • 3,283
  • 4
  • 35
  • 73

1 Answers1

1

It seems, that you are looking for DirectoryInfo class: having, say, c:\MyData\MyPath\10folder you want to match 10 within 10folder. If it's your case:

static void SearchFolder(string searchDirectory) {
  var folders = Directory
    .EnumerateDirectories(searchDirectory)
    .Where(path => new DirectoryInfo(path).Name.StartsWith("10"));

  foreach (var folderName in folders)
    Console.WriteLine($"found: {folderName}");
}

In case you want regular expression, put it as

     .Where(path => Regex.IsMatch(new DirectoryInfo(path).Name, "10.*"));

Please, note that "10.*" pattern means starting from 10, when you original pattern @"\10.*" uses \1 which means 1st capturing group.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • It looked like the string had escaping backslash \\. Your suggestion didn't quite answer the direct question about how to build a dynamic path pattern, but it solved my problem. Thanks! – mottosson Jun 27 '19 at 13:24
  • @mottosson: please, note, that valid path can have *different* separators: `Path.AltDirectorySeparatorChar` and `Path.DirectorySeparatorChar`, e.g. `c:/MyData/MyPath/10folder` is a valid path.That's why hardcoding *back slash* can be a bad idea, when `DirectoryInfo` works with whatever separators – Dmitry Bychenko Jun 27 '19 at 13:27