Parsing an canonical path with wildcards

2019-07-06 20:59发布

I am writing the C# function which retrieves some files matched pattern.

Input : C:\abc*\abc?\testfile.*
Output : All files matched.

I thought I could make it by recursion. But it was not easy :(

Do you have a nice algorithm?

Update:
I made it. Thanks Kieren :)

void PrintAllFiles(DirectoryInfo currentDir, 
                   string currentPattern, string nextPatten)
{
  DirectoryInfo[] dis = currentDir.GetDirectories(currentPattern);

  if (dis.Length > 0)
  {
    string[] remainPattern = nextPatten.Split("\\".ToCharArray());
    if (remainPattern.Length > 0)
    {
      foreach (DirectoryInfo di in dis)
      {
        PrintAllFiles(di, remainPattern.First(), 
                       string.Join("\\", remainPattern.Skip(1).ToArray()));
      }
    }
  }

  FileInfo[] fis = currentDir.GetFiles(currentPattern);
  foreach (FileInfo fi in fis)
  {
    Console.WriteLine(fi.DirectoryName + "\\" + fi.Name);
  }
}

1条回答
该账号已被封号
2楼-- · 2019-07-06 21:35

The easiest is by using recursion; you would get the base folder first (C:\) then pass C:\ as the current path, abc* to the 'current pattern' parameter, and abc?\testfile.* to the 'next patterns' parameter.

If that method found a folder matching, say 'c:\abc123': it would call the method again, with C:\abc123 as the current path, abc? as the 'current pattern', and testfile.* as the 'next patterns'.

By the time you have no more patterns to match, you can stop the recursion and declare success :)

Hope that helps.

查看更多
登录 后发表回答