Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C语言中使用通配符解析相对路径#_C#_.net_Wildcard_Relative Path_Path Combine - Fatal编程技术网

C# 在C语言中使用通配符解析相对路径#

C# 在C语言中使用通配符解析相对路径#,c#,.net,wildcard,relative-path,path-combine,C#,.net,Wildcard,Relative Path,Path Combine,在C#中,如果我有一个目录路径和一个带有通配符的相对文件路径,例如 “c:\foo\bar”和。\blah\*.cpp“ 有没有一种简单的方法来获取绝对文件路径列表?e、 g {“c:\foo\blah\a.cpp”,“c:\foo\blah\b.cpp”} 背景 有一个源代码树,其中任何目录都可以包含生成定义文件。此文件使用带有通配符的相对路径来指定源文件的列表。任务是为每个构建定义文件生成所有源文件的绝对路径列表。这很简单 using System.IO; . .

在C#中,如果我有一个目录路径和一个带有通配符的相对文件路径,例如

“c:\foo\bar”
。\blah\*.cpp“

有没有一种简单的方法来获取绝对文件路径列表?e、 g

{“c:\foo\blah\a.cpp”,“c:\foo\blah\b.cpp”}

背景

有一个源代码树,其中任何目录都可以包含生成定义文件。此文件使用带有通配符的相对路径来指定源文件的列表。任务是为每个构建定义文件生成所有源文件的绝对路径列表。

这很简单

using System.IO;
      .
      .
      .
string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly);

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

// 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 );

System.IO.Directory.EnumerateFiles允许您在searchpattern参数中指定通配符,请参阅:并将返回绝对值paths@Polity,System.ArgumentException:搜索模式不能包含“.”若要向上移动directoriesPath.GetFullPath()将抛出ArgumentException:如果路径包含任何通配符,则路径中包含非法字符。您是对的,我更新了我的代码,这样相对搜索模式首先被划分为目录和文件信息,然后绝对路径被确定!甚至更好,而不是
string relDir=originalPattern.Substring(0,originalPattern.Length-pattern.Length)我们可以使用
字符串relDir=Path.GetDirectoryName(originalPattern)
这很有效,但只有在相对路径的目录名中没有使用通配符时,如问题提供的特定示例中所示。