Skip to main content
 首页 » 编程设计

c#之在字符串中查找无限文件路径

2024年02月13日22luoye11

我有这些由闭源第三方软件生成的错误消息,我需要从中提取文件路径。

上述文件路径为:

  • 不受限制(即不被引号、圆括号、方括号等包围)
  • root(即以 <letter>:\ 开头,例如 C:\ )
  • 不保证有文件扩展名
  • 表示保证在运行提取代码的计算机上存在的文件(仅文件,不包括目录)。
  • 由任何有效字符组成,包括空格,使它们难以被发现(例如 C:\This\is a\path \but what is an existing file path here )

需要注意的是,每条消息可以有 0 个或多个文件路径。

如何在错误消息中找到这些文件路径?

我在下面提出了一个答案,但我觉得有更好的方法来解决这个问题。

请您参考如下方法:

对于每个匹配项,期待下一个“\”字符。所以你可能会得到“c:\mydir\”。检查该目录是否存在。然后找到下一个 \,给出 "c:\mydir\subdir`。检查那个路径。最终你会找到一个不存在的路径,或者你会开始下一场比赛。

此时,您知道要查找的目录。然后只需调用 Directory.GetFiles 并匹配与从您找到的最后一个路径开始的子字符串匹配的最长文件名。

这应该最大限度地减少回溯。

这是如何做到的:

static void FindFilenamesInMessage(string message) { 
    // Find all the "letter colon backslash", indicating filenames. 
    var matches = Regex.Matches(message, @"\w:\\", RegexOptions.Compiled); 
 
    // Go backwards. Useful if you need to replace stuff in the message 
    foreach (var idx in matches.Cast<Match>().Select(m => m.idx).Reverse()) { 
        int length = 3; 
        var potentialPath = message.Substring(idx, length); 
        var lastGoodPath = potentialPath; 
 
        // Eat "\" until we get an invalid path 
        while (Directory.Exists(potentialPath)) { 
            lastGoodPath = potentialPath; 
            while (idx+length < message.Length && message[idx+length] != '\\') 
                length++; 
 
            length++; // Include the trailing backslash 
 
            if (idx + length >= message.Length) 
                length = (message.Length - idx) - 1; 
 
            potentialPath = message.Substring(idx, length); 
        } 
 
        potentialPath = message.Substring(idx); 
 
        // Iterate over the files in directory we found until we get a match 
        foreach (var file in Directory.EnumerateFiles(lastGoodPath) 
                                      .OrderByDescending(s => s.Length)) { 
            if (!potentialPath.StartsWith(file)) 
                continue; 
 
            // 'file' contains a valid file name 
            break; 
        } 
    } 
}