12

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.

sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
NS.X.
  • 2,072
  • 5
  • 28
  • 55
  • System.IO.Directory.EnumerateFiles allows you to specify wildcards in the searchpattern param, see: http://msdn.microsoft.com/en-us/library/dd413233.aspx and will return absolute paths – Polity Dec 15 '11 at 08:48
  • @Polity, System.ArgumentException: Search pattern cannot contain ".." to move up directories – NS.X. Dec 15 '11 at 19:29

2 Answers2

4

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 );
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
  • Path.GetFullPath() throws ArgumentException: Illegal characters in path, if the path contains any wildcard. – NS.X. Dec 15 '11 at 19:22
  • You're right, I updated my code so that the relative search pattern is first divided into directory- and file-information and afterwards the absolute path is determined – Stephan Bauer Dec 16 '11 at 07:23
  • It works! Even better, rather than `string relDir = originalPattern.Substring ( 0, originalPattern.Length - pattern.Length );` We can use `string relDir = Path.GetDirectoryName(originalPattern);` – NS.X. Dec 17 '11 at 04:22
  • This works well, but only when no wildcards are used in the directory names of the relative path, like in the specific example provided by the question. – sɐunıɔןɐqɐp Feb 07 '19 at 07:41
3

It's simple.

using System.IO;
      .
      .
      .
string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly);
Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76
Greg Harris
  • 114
  • 1
  • 8