.net 确保路径不为';我不能上一层楼
我想确保.net 确保路径不为';我不能上一层楼,.net,validation,path,.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 = "subfo
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)
但是我找不到virtualPath.GetFullPath()
或类似的东西。我可以禁止。/
字符串中的任何位置,但可能有一种方法可以通过奇怪的间距、特殊字符等来避免这种情况。您可以使用它将所有路径转换为绝对路径,然后只需比较字符串。即:
string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";
string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);
if (!relativePathRooted.StartsWith(basePathRooted))
//Fail
可以使用将所有路径转换为绝对路径,然后只比较字符串。即:
string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";
string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);
if (!relativePathRooted.StartsWith(basePathRooted))
//Fail
所以
basePathRooted==“C:\myFolder”
和relativeApprooted==“C:\ProgramFiles(x86)\Microsoft Visual Studio 9.0\Common7\IDE\which\u user\u input”
。不过,我喜欢你的想法,而且string relativepathoted=Path.GetFullPath(basePath+relativePath)
应该可以用。事实证明,我没有提前准备basePath
,所以类似下面的东西很好用:Path.GetFullPath(relativePath).StartsWith(Path.GetFullPath(“.”)
sobasePathRooted==“C:\myFolder”
和RelativeApprothoted==“C:\Program Files(x86)\Microsoft Visual Studio 9.0\Common7\IDE\which\u user\u input”
。不过,我喜欢你的想法,而且string relativepathoted=Path.GetFullPath(basePath+relativePath)
应该可以用。事实证明,我事先没有basePath
,所以类似下面的东西很好用:Path.GetFullPath(relativePath).StartsWith(Path.GetFullPath(“.”)