简体   繁体   中英

Combine an absolute path with a relative path

Let's say I have defined an absolute path

string abs = "X:/A/B/Q";

and a relative path

string rel = "../B/W";

How do I combine these two so that it results in following output?

"X:/A/B/W"

I already tried Path.Combine() , but not successfully.

Try this:

string abs = "X:/A/B/Q";
string rel = "../../B/W";
var path = Path.GetFullPath(Path.Combine(abs,rel));

It will give you full absolute path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

I improve the above code from @wudzik

public static string ConvertRelativePathToAbsolutePath(string basePath, string path)
{
    if (System.String.IsNullOrEmpty(basePath) == true || System.String.IsNullOrEmpty(path) == true) return "";
    //Gets a value indicating whether the specified path string contains a root.
    //This method does not verify that the path or file name exists.
    if (System.IO.Path.IsPathRooted(path) == true)
    {
        return path;
    }
    else
    {
        return System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, path));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM