Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 确保路径不为';我不能上一层楼_.net_Validation_Path - Fatal编程技术网

.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(“.”)
so
basePathRooted==“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(“.”)