How to get the absolute path to the file from the 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 the Magic method? Hopefully not too complicated code.

Is there a way to " Magic " in the .NET Framework?

+7
c # filepath
source share
2 answers

If you look at the Path class, there are several methods that should help:

 Path.Combine 

and

 Path.GetFullPath 

So:

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

Although the second step is not strictly necessary, it will give you a β€œcleaner” way if you type.

+11
source share

Since Path.Combine does not work in all cases, this is a more complicated function Path.Combine

 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" , not as expected @"C:\foo\bar"

0
source share

All Articles