其他提示

您只需调用 Path.GetFullPath(),然后检查它是否以您信任的 rootPath 开头。如果您倾向于偏执,请检查 rootPath 是否已植根。

public Boolean IsPathSafe(String rootPath, String relativePath)
{
  return rootPath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
    Path.IsPathRooted(rootPath) &&
    Patch.Combine(rootPath, relativePath).GetFullPath().StartsWith(rootPath);
}

有关第一次测试的解释,请参阅Alex Martelli对technophile答案的评论。

你可以做的一件事就是计算反斜杠的数量( \ )和双点( .. ),并确保双倍的数量 - 点小于反斜杠的数量。为了超越文件夹结构中的 rootPath ,你需要至少与双点一样多的反斜杠 - 因此,如果你只允许 relativePath 至少还有一个反斜杠,你应该是安全的。

scroll top