In C#, if I have a directory path and a relative file path with wildcard, e.g.
"c:\foo\bar"
and "..\blah\*.cpp"
Is there a simple way to get the list of absolute file paths? e.g.
{ "c:\foo\blah\a.cpp", "c:\foo\blah\b.cpp" }
Background
There is a source code tree, where any directory can contain a build definition file. This file uses relative paths with wildcards to specify a list of source files. The task is to generate a list of absolute paths of all source files for each one of these build definition files.
The ? wildcard character matches a single character. The * wildcard character matches zero or more characters. The ** wildcard character sequence matches a partial path.
An absolute path is defined as specifying the location of a file or directory from the root directory(/). In other words,we can say that an absolute path is a complete path from start of actual file system from / directory. Relative path. Relative path is defined as the path related to the present working directly(pwd) ...
A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
You can get the absolute path first and then enumerate the files inside the directory matching the wildcard:
// 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 );
It's simple.
using System.IO;
.
.
.
string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With