Cha*_*lie 21
不幸的是,它不是那么简单StartsWith
.
这是一个更好的答案,改编自这个重复的问题.我已经把它作为一种易于使用的扩展方法.同样使用暴力catch
作为访问文件系统的任何方法都可能因用户权限而失败.
public static bool IsSubDirectoryOf(this string candidate, string other)
{
var isChild = false;
try
{
var candidateInfo = new DirectoryInfo(candidate);
var otherInfo = new DirectoryInfo(other);
while (candidateInfo.Parent != null)
{
if (candidateInfo.Parent.FullName == otherInfo.FullName)
{
isChild = true;
break;
}
else candidateInfo = candidateInfo.Parent;
}
}
catch (Exception error)
{
var message = String.Format("Unable to check directories {0} and {1}: {2}", candidate, other, error);
Trace.WriteLine(message);
}
return isChild;
}
Run Code Online (Sandbox Code Playgroud)
任何基于字符串的解决方案都可能遭受目录遍历攻击或诸如斜杠之类的正确性问题。不幸的是,.NET Path
类没有提供此功能,但是Uri
该类提供了.NET 的形式Uri.IsBaseOf()
。
Uri potentialBase = new Uri(@"c:\dir1\");
Uri regular = new Uri(@"c:\dir1\dir2");
Uri confusing = new Uri(@"c:\temp\..\dir1\dir2");
Uri malicious = new Uri(@"c:\dir1\..\windows\system32\");
Console.WriteLine(potentialBase.IsBaseOf(regular)); // True
Console.WriteLine(potentialBase.IsBaseOf(confusing)); // True
Console.WriteLine(potentialBase.IsBaseOf(malicious)); // False
Run Code Online (Sandbox Code Playgroud)
Cap*_*der -3
这是一种方法,您有路径 A 和 B,使用 Path.GetFullPath() 函数将它们转换为完整路径。接下来检查其中一个完整路径是否是另一个完整路径的起始子字符串。
那么那就是
if (Path.GetFullPath(A).StartsWith(Path.GetFullPath(B)) ||
Path.GetFullPath(B).StartsWith(Path.GetFullPath(A)))
{ /* ... do your magic ... */ }
Run Code Online (Sandbox Code Playgroud)