c# - 通过比较部分目录路径来匹配子目录

标签 c# .net regex string

我可能没有把标题说得太好,但希望我的解释能够说明问题。

基本上,当给定另一个路径进行比较时,我必须找出子目录的名称(不包括文件名)。例如,

Given: "C:\Windows\System32\catroot\sys.dll"

Compare: "C:\Windows"

Matched String: "\System32\catroot"

这是另一个例子:

Given: "C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"

Compare: "C:\Windows\System32"

Matched String: "\WindowsPowerShell\v1.0\Examples"

执行此匹配的最佳方式是什么?

最佳答案

您可能还需要考虑特殊情况,例如:

  • 相对路径

  • 具有短名称的路径,例如 C:\PROGRA~1 代表 C:\Program Files

  • 非规范路径 (C:\Windows\System32\..\..\file.dat)

  • 使用备用分隔符的路径(/ 而不是 \)

一种方法是在比较之前使用 Path.GetFullPath 转换为规范的完整路径

例如

string toMatch = @"C:\PROGRA~1/";
string path1 = @"C:/Program Files\Common Files\..\file.dat";
string path2 = @"C:\Program Files\Common Files\..\..\file.dat";

string toMatchFullPath = Path.GetFullPath(toMatch);
string fullPath1 = Path.GetFullPath(path1);
string fullPath2 = Path.GetFullPath(path2);

// fullPath1 = C:\Program Files\file.dat
// toMatchFullPath = C:\Program Files\
if (fullPath1.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase))
{
    // path1 matches after conversion to full path
}

// fullPath2 = C:\file.dat
// toMatchFullPath = C:\Program Files\
if (fullPath2.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase))
{
    // path2 does not match after conversion to full path
}

关于c# - 通过比较部分目录路径来匹配子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12313971/

相关文章:

c# - 使用 JSON 时如何让 ServiceStack 将 Guids 格式化为破折号?

c# - WPF 复制将正多边形混合到应用程序中

.net - 调试 .NET 框架源代码

c# - IIS 7 配置数据库 : Setting the framework version and the managed pipeline mode programmatically

Python 正则表达式 : how to excluding superstrings?

regex - Dreamweaver 用正则表达式替换

c# - Avalondock-某些面板的布局恢复延迟

javascript - 当路由参数和地址无效时,Angular 2不会重定向到404页面

c# - ASP.NET MVC 2.0 : Simple Model Binding not working/binding as it should

javascript - js - match() 未正确返回值