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?
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"
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.