问题描述
在C#中,如果我有目录路径和带通配符的相对文件路径,例如
In C#, if I have a directory path and a relative file path with wildcard, e.g.
"c:\ foo \ bar"
和".. \ 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"}
背景
有一个源代码树,其中任何目录都可以包含构建定义文件.该文件使用带通配符的相对路径来指定源文件列表.任务是为这些构建定义文件中的每一个生成所有源文件的绝对路径的列表.
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.
推荐答案
您可以先获取绝对路径,然后枚举与通配符匹配的目录中的文件:
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 );
这篇关于在C#中使用通配符解析相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!