Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute Path from Relative Path with a different current folder

Tags:

c#

.net

path

I need to get an absolute path from a relative path, but using a folder other than where the assembly is executing from to resolve "." and "..". Path.GetFullPath does not provide such an overload.

For example, say I have the following path:

..\MyOtherFolder\foo.bar

And the folder the assembly is executing from is:

c:\users\me\desktop\source\myproj\bin\debug\

but it could, in practice, be located anywhere.

I want to specify the "current" folder as c:\test so the ".." resolves to "c:\".

Does anyone know if this is built into the .NET framework anywhere? If not, I plan on making a Utility method, but I thought I'd check first (especially since there's no static extension methods...).

EDIT:

Path.Combine will not work. All this method essentially does is concatenate the two strings.

like image 802
MgSam Avatar asked Dec 08 '25 17:12

MgSam


2 Answers

Have you tried

Path.GetFullPath(Path.Combine(@"C:\test", @"..\MyOtherFolder\foo.bar"))

That should do the trick.

like image 113
Marcus Avatar answered Dec 10 '25 06:12

Marcus


public string FullPathRelativeTo(string root, string partialPath)
{
    string oldRoot = Directory.GetCurrentDirectory();
    try {
        Directory.SetCurrentDirectory(root);
        return Path.GetFullPath(partialPath);
    }
    finally {
        Directory.SetCurrentDirectory(oldRoot);
    }
}
like image 44
plinth Avatar answered Dec 10 '25 06:12

plinth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!