Убедитесь, что путь не идет вверх по уровню - PullRequest
1 голос
/ 12 января 2011

Я хочу убедиться, что 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 Ответ

1 голос
/ 12 января 2011

Вы можете использовать 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...