I need a bullet proof way to combine a root and a relative path to form a FQ
rooted path (similar to a VDir in IIS). Path.Combine alone will not do the
job in all cases. I also need to be sure the no funny business can go on in
the passed "path" that would produce a path not in the root (i.e.
"..\..\dir1"). Here is my first stab at it, but not sure if this is too
much or not enouph to ensure this. Any thoughts are welcome. TIA.
/// <summary>
/// Combines the root and path to ensure the path always relative to
the root and not below it or in some other root.
/// This does not check if the resulting path exists or if access is
allowed.
/// Path can not contain ".." anywhere in the path. Path can not be
rooted, it must be a relative path.
/// </summary>
/// <param name="root"></param>
/// <param name="path"></param>
/// <returns></returns>
public static string CombineRootAndPath(string root, string path)
{
// Path can not be rooted. Must be realitive.
// Path can not contain ".." anywhere.
if ( root == null )
return null;
if ( path == null )
return null;
if ( ! Path.IsPathRooted(root) )
return null;
if ( root.EndsWith(@"\"))
root = root + @"\";
path = path.Trim();
if ( Path.IsPathRooted(path) )
return null;
string fullPath = Path.Combine(root, path);
// Final test to make sure nothing unexpected in path would
Combine
// to produce something outside the root.
if ( ! fullPath.StartsWith(root) )
return null;
if ( path.Contains("..") )
return null;
return fullPath;
}
--
William Stacey [MVP]