【问题标题】:Resolving relative paths with wildcards in C#在 C# 中使用通配符解析相对路径
【发布时间】:2012-01-20 23:33:54
【问题描述】:

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

"c:\foo\bar""..\blah\*.cpp"

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

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

背景

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

【问题讨论】:

  • System.IO.Directory.EnumerateFiles 允许您在 searchpattern 参数中指定通配符,请参阅:msdn.microsoft.com/en-us/library/dd413233.aspx 并将返回绝对路径
  • @Polity, System.ArgumentException:搜索模式不能包含“..”以向上移动目录

标签: c# .net wildcard relative-path path-combine


【解决方案1】:

可以先获取绝对路径,再枚举目录内匹配通配符的文件:

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

【讨论】:

  • Path.GetFullPath() throws ArgumentException: Illegal characters in path, if the path contains any wildcard.
  • 你说得对,我更新了我的代码,使相对搜索模式首先分为目录和文件信息,然后确定绝对路径
  • 有效!甚至更好,而不是string relDir = originalPattern.Substring ( 0, originalPattern.Length - pattern.Length ); 我们可以使用string relDir = Path.GetDirectoryName(originalPattern);
  • 这很好用,但只有在相对路径的目录名称中没有使用通配符时,如问题提供的具体示例中。
【解决方案2】:

很简单。

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

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多