我可能没有把标题说得太好,但希望我的解释能够说明问题。
基本上,当给定另一个路径进行比较时,我必须找出子目录的名称(不包括文件名)。例如,
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/