开发者

File names matching "..\ThirdParty\dlls\*.dll"

Is there an easy way to get a list of filenames that matach a filename pattern including references to parent directory? What I want is for "..\ThirdParty\dlls\*.dll" to return a collection like ["..\ThirdParty\dlls\one.dll", "..\ThirdParty\dlls\two.dll", ...]

I can find several questions relating matching file开发者_运维技巧s names including full path, wildcards, but nothing that includes "..\" in the pattern. Directory.GetFiles explicitly disallows it.

What I want to do with the names is to include them in a zip archive, so if there is a zip library that can understand relative paths like this I am happier to use that.

The pattern(s) are coming from an input file, they are not known at compile time. They can get quite complex, e.g ..\src\..\ThirdParty\win32\*.dll so parsing is probably not feasible.

Having to put it in zip is also the reason I am not very keen on converting the pattern to fullpath, I do want the relative paths in zip.

EDIT: What I am looking for really is a C# equivalent of /bin/ls.


static string[] FindFiles(string path)
{
    string directory = Path.GetDirectoryName(path); // seperate directory i.e. ..\ThirdParty\dlls
    string filePattern = Path.GetFileName(path); // seperate file pattern i.e. *.dll

    // if path only contains pattern then use current directory
    if (String.IsNullOrEmpty(directory))
        directory = Directory.GetCurrentDirectory();

    //uncomment the following line if you need absolute paths
    //directory = Path.GetFullPath(directory); 

    if (!Directory.Exists(directory))      
        return new string[0];

    var files = Directory.GetFiles(directory, filePattern); 
    return files;
}


There is the Path.GetFullPath() function that will convert from relative to absolute. You could use it on the path part.

string pattern = @"..\src\..\ThirdParty\win32\*.dll";

string relativeDir = Path.GetDirectoryName(pattern);
string absoluteDir = Path.GetFullPath(relativeDir);
string filePattern = Path.GetFileName(pattern);

foreach (string file in Directory.GetFiles(absoluteDir, filePattern))
{

}


If I understand you correctly you could use Directory.EnumerateFiles in combination with a regular expression like this (I haven't tested it though):

var matcher = new Regex(@"^\.\.\\ThirdParty\\dlls\\[^\\]+.dll$");
foreach (var file in Directory.EnumerateFiles("..", "*.dll", SearchOption.AllDirectories)
{
    if (matcher.IsMatch(file))
        yield return file;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜