Resolving relative paths with wildcards in C#

不羁的心 提交于 2020-05-12 11:45:21

问题


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.


回答1:


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



回答2:


It's simple.

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


来源:https://stackoverflow.com/questions/8517260/resolving-relative-paths-with-wildcards-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!