0

I need to get a list of files and directories corresponding to a given arbitrary path, e.g. \foo\bar\*.txt. Essentially, the same result as would dir with this path produce.

Ideally, it should be an array of FileSystemInfo rather than of expanded file names/path strings.

When starting from a certain root directory, the solution is simply

a = new DirectoryInfo(root_path);
return a.GetFileSystemInfos(my_pattern);

But this time I don't have a defined root_path; my_pattern is arbitrary and can be relative, absolute or UNC path.

For simplicity, let's assume I don't need to parse wildcards recursively, i.e. paths\*\like*\this?.txt. Wildcards can only appear in the last part (but the pattern can still match a file or a directory).

I could split my_pattern into 'directory' and 'file' parts (using IO.Path.GetDirectoryName() etc., and then treat them like above. But this feels overcomplicated for the task, given that I have to deal separately with cases when one of such parts is empty.

If I could get DirectoryInfo for the 'computer root', from which even absolute paths would be valid, it would be easy, but this doesn't seem to be possible.

It feels like this should be a one-liner, but I can't find it in .NET...

Zeus
  • 1,052
  • 1
  • 9
  • 18

1 Answers1

1

Annoyingly that's basically all you have in in the .NET Framework. You can do as you suggest e.g.

var directory = Path.GetDirectoryName(path);
var file = Path.GetFileName(path);

// Determine if the path is a file path with wildcards
if (!string.IsNullOrEmpty(directory) 
    &&  !string.IsNullOrEmpty(file) 
    && (file.Contains("*") || file.Contains("?")))
{
    foreach (var match in Directory.EnumerateFiles(directory, file))
    {
        DeleteFile(match);
    }
}
else
{
    // TODO handling of path without wildcards
}

The alternative is to use the non-portable Windows API FindFirstFileEx (etc.) functions.

Ananke
  • 1,250
  • 9
  • 11
  • Thanks. It's strange MS didn't think of making, say, a static method like `Directory.GetFileSystemInfos()` for this common purpose; but this is not the first time I run into inexplicable limitations in .NET... Re your example, I don't thing it's necessary to treat wildcard-conraining paths separately: a literal exact path is still a match on itself. But empty `directory` still needs protection. – Zeus Jun 04 '18 at 01:41