I want to make sure relativePath
doesn't go up a folder past basePath
. Is there any reliable way to detect this?
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;
I'm thinking something like the following could work
Path.GetFullPath(basePath + relat开发者_C百科ivePath).StartsWith(basePath)
But I couldn't find a VirtualPathUtility.GetFullPath()
or something similar. I could disallow ../
anywhere in the string, but there may be a way to circumvent that with strange spacing, special characters, etc.
You can use Path.GetFullPath to convert all your paths to absolute paths, and then just compare the strings. That is:
string basePath = "/myFolder/";
string relativePath = "whatever_user_inputs";
string basePathRooted = Path.GetFullPath(basePath);
string relativePathRooted = Path.GetFullPath(relativePath);
if (!relativePathRooted.StartsWith(basePathRooted))
//Fail
精彩评论