开发者

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 开发者_JAVA技巧too complicated code.

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


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜