确保路径不上升

时间:2011-01-12 18:41:51

标签: .net validation path

我想确保relativePath不会超过basePath之后的文件夹。有没有可靠的方法来检测这个?

string basePath = "/myfolder/";
string relativePath;

// Invalid
relativePath = "../foo";
relativePath = "subfolder/../../bar";

// Valid, but if too hard this can also be invalid
relativePath = "subfolder/../subfolder2";

// Valid
relativePath = "subfolder/another..folder/";
relativePath = "subfolder/..anotherFolder/";

// There may be ways to circumvent that I haven't thought of...
// Maybe some of these would work
relativePath = " ../";
relativePath = ".. /";

// fullPath should not be above basePath
string fullPath = basePath + relativePath;

我正在考虑以下内容可能会起作用

Path.GetFullPath(basePath + relativePath).StartsWith(basePath)

但我找不到VirtualPathUtility.GetFullPath()或类似的东西。我可以在字符串中的任何地方禁止../,但可能有办法用奇怪的间距,特殊字符等来规避它。

1 个答案:

答案 0 :(得分:1)

您可以使用Path.GetFullPath将所有路径转换为绝对路径,然后只比较字符串。那就是:

string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";

string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);

if (!relativePathRooted.StartsWith(basePathRooted))
     //Fail