I usually use this simple code to check this problem:
(I type it directly so it may not compile, it's just to give you the idea)
private string getPath(string basePath, string fileName)
{
var fullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, fileName));
if (fullPath.StartsWith(basePath))
return fullPath;
return null;
}
The goal is to use Path.GetFullPath
. This method will translate any /../ etc to a complete path. Then check that the returned path is in the allowed directory.
Be carefull that this method may returns slighty different path than expected, read MSDN for detailed explanations