Resolving relative paths with wildcards in C #

In C #, if I have a directory path and relative file path with a wildcard, e.g.

"c:\foo\bar" and "..\blah\*.cpp"

Is there an easy way to get a list of absolute file paths? eg

{ "c:\foo\blah\a.cpp", "c:\foo\blah\b.cpp" }

Background

There is a source tree tree in which any directory can contain an assembly definition file. This file uses relative wildcard paths to indicate a list of source files. The challenge is to create a list of the absolute paths of all source files for each of these assembly definition files.

+9
source share
2 answers

First you can get the absolute path, and then list the files inside the directory matching the pattern:

 // input string rootDir = @"c:\foo\bar"; string originalPattern = @"..\blah\*.cpp"; // Get directory and file parts of complete relative pattern string pattern = Path.GetFileName (originalPattern); string relDir = originalPattern.Substring ( 0, originalPattern.Length - pattern.Length ); // Get absolute path (root+relative) string absPath = Path.GetFullPath ( Path.Combine ( rootDir ,relDir ) ); // Search files mathing the pattern string[] files = Directory.GetFiles ( absPath, pattern, SearchOption.TopDirectoryOnly ); 
+3
source

It's simple.

 using System.IO; . . . string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly); 
+1
source

All Articles