By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,320 Members | 2,109 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,320 IT Pros & Developers. It's quick & easy.

Combine root and path.

P: n/a
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]

Nov 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Removed "if ( root.EndsWith)"

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;
try
{
if ( !Path.IsPathRooted(root) )
return null;
}
catch
{
return null;
}
//if ( root.EndsWith(@"\"))
// root = root + @"\";
path = path.Trim();
try
{
if ( Path.IsPathRooted(path) )
return null;
}
catch
{
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]

Nov 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.