October 13, 2010

Path.Combine

See here for a description of the behaviour of this method.
Following method resolves some weaknesses in the static method "Path.Combine" found in the System.IO namespace.
public static string PathCombine(string rootPath, string relativePath)
{
    Debug.Assert(rootPath != null);
    Debug.Assert(relativePath != null);

    string res = string.Empty;
    if (rootPath.EndsWith(":"))
    {
        rootPath += @"\";
    }
    // remove initial single '\' or '/' from relative path
    if (relativePath.StartsWith(@"\") || 
        relativePath.StartsWith(@"/"))
    {
        if (! (relativePath.StartsWith(@"\\") || 
               relativePath.StartsWith(@"//")))
        {
           relativePath = relativePath.Substring(1); 
        }
    }
    res = Path.Combine(rootPath, relativePath);
    res = res.Replace('/', '\\'); // replace '/' with '\'
    return res;
}

No comments: