How to get absolute file path from base path and relative containing ".."?

string basepath = @"C:\somefolder\subfolder\bin"; // is defined in runtime
string relative = @"..\..\templates";

string absolute = Magic(basepath, relative); // should be "C:\somefolder\templates"

Can you help me with Magic method? Hopefully not too complicated code.

Is there the "Magic" method in .NET Framework?

Answers


If you look at the Path class there are a couple of methods which should help:

Path.Combine

and

Path.GetFullPath

So:

string newPath = Path.Combine(basepath, relative);
string absolute = Path.GetFullPath(newPath);

Although the second step isn't strictly needed - it would give you a "cleaner" path if you were printing out say.


Because Path.Combine does not work in all cases here is a more complex function :-)

static string GetFullPath(string maybeRelativePath, string baseDirectory) {
    if (baseDirectory == null) baseDirectory = Environment.CurrentDirectory;
    var root = Path.GetPathRoot(maybeRelativePath);
    if (string.IsNullOrEmpty(root)) 
        return Path.GetFullPath(Path.Combine(baseDirectory, maybeRelativePath));
    if (root == "\\") 
        return Path.GetFullPath(Path.Combine(Path.GetPathRoot(baseDirectory), maybeRelativePath.Remove(0, 1)));
    return maybeRelativePath;
}

Path.Combine(@"C:\foo\",@"\foo\bar") returns @"\foo\bar" and not as expected @"C:\foo\bar"


Need Your Help

Why my custom style are not applied in the action bar?

android android-layout android-actionbar

I have searching a lot a method to customize the Action Bar.

'rails generate' commands hang when trying to create a model

ruby-on-rails ruby-on-rails-4

I'm new to rails and decided this morning to dump my whole database design/model and start over. And being a noob, I'm sure did it incorrectly.