【问题标题】:File names matching "..\ThirdParty\dlls\*.dll"与“..\ThirdParty\dlls\*.dll”匹配的文件名
【发布时间】:2011-10-01 07:38:30
【问题描述】:

有没有一种简单的方法来获取与文件名模式匹配的文件名列表包括对父目录的引用?我想要的是让"..\ThirdParty\dlls\*.dll" 返回一个像["..\ThirdParty\dlls\one.dll", "..\ThirdParty\dlls\two.dll", ...] 这样的集合

我可以找到几个与匹配文件名相关的问题,包括完整路径、通配符,但模式中没有包含“..\”的问题。 Directory.GetFiles 明确禁止它。

我想要对这些名称执行的操作是将它们包含在 zip 存档中,所以如果有一个 zip 库可以理解这样的相对路径,我会更乐意使用它。 p>

模式来自输入文件,它们在编译时未知。它们可能会变得非常复杂,例如 ..\src\..\ThirdParty\win32\*.dll 所以解析可能不可行。

必须把它放在 zip 中也是我不太热衷于将模式转换为全路径的原因,我确实想要 zip 中的相对路径。

编辑:我真正在寻找的是 /bin/ls 的 C# 等价物。

【问题讨论】:

    标签: c# filenames glob


    【解决方案1】:
    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;
    }
    

    【讨论】:

    • Path 是我需要的 :) 唯一的问题是这返回了 absolute 名称,而我需要 relative。删除 Path.GetFullPath 电话可以解决这个问题。可以相应地更改您的答案,使其完全符合我的要求吗?
    • @HemalPandya 我认为对其他人来说,更通用的方法可能更相关。所以让我们保持原样。
    • 但是如果没有改变它不是我的问题的正确答案,因为我特别要求相对路径:(也许你可以改变它,让它返回相对路径,并说明如何获得在其他情况下可能更相关的完整路径?
    【解决方案2】:

    有一个 Path.GetFullPath() 函数可以从相对转换为绝对。您可以在路径部分使用它。

    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))
    {
    
    }
    

    【讨论】:

    • 对不起,我显然和你同时准备了答案……总之,你的更完整。
    【解决方案3】:

    如果我理解正确,您可以将Directory.EnumerateFiles 与这样的正则表达式结合使用(虽然我还没有测试过):

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

    【讨论】:

    • 我使用的是 .NET 3.5,而这个功能似乎只有 4+。此外,要匹配的模式在编译时不可用,并且可能包含任意路径("..\..\bin\..\lib\x.dll"...它很丑但发生了),这种方法将需要我解析不可行的模式。另外我不知道函数返回的名称是否是相对的。但是您的回答在我的问题中显示了一些模棱两可,因此可以帮助我澄清。
    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2019-02-07
    相关资源
    最近更新 更多