Resolving relative path with wildcard in C#

In C# if I have a directory path and a relative file path with wildcard, "c:foobar" and "..blah*.cpp" , is there a simple way to get the list of absolute file paths, { "c:fooblaha.cpp", "c:fooblahb.cpp" } ?

Background: there is a source tree that any directory can contain build definition file, which use relative path with wildcard to specify source files. The task here is to generate a list of absolute path of all source files for each build definition file.


您可以先获取绝对路径,然后枚举匹配通配符的目录中的文件:

// input
string rootDir = @"c:foobar"; 
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 );

这很简单。

using System.IO;
      .
      .
      .
string[] files = Directory.GetFiles(@"c:", "*.txt", SearchOption.TopDirectoryOnly);
链接地址: http://www.djcxy.com/p/10220.html

上一篇: 在C#中使用表达式树的ByRef参数

下一篇: 在C#中使用通配符解析相对路径