Ondrej Janacek
Ondrej Janacek

Reputation: 12626

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.

Upvotes: 1

Views: 1263

Answers (2)

oudi
oudi

Reputation: 677

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));
    }
}

Upvotes: 0

Kamil Budziewski
Kamil Budziewski

Reputation: 23117

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

Upvotes: 4

Related Questions