Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving relative paths with wildcards in C#

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.

like image 202
NS.X. Avatar asked Dec 15 '11 08:12

NS.X.


People also ask

What is double asterisk in path?

The ? wildcard character matches a single character. The * wildcard character matches zero or more characters. The ** wildcard character sequence matches a partial path.

What is absolute path and relative path in C?

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) ...

What is relative path in file handling?

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.


2 Answers

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 );
like image 112
Stephan Bauer Avatar answered Sep 20 '22 05:09

Stephan Bauer


It's simple.

using System.IO;
      .
      .
      .
string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly);
like image 29
Greg Harris Avatar answered Sep 22 '22 05:09

Greg Harris