3

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
MgSam
  • 12,139
  • 19
  • 64
  • 95
  • Possible duplicate [how to convert relative path to absolute path in windows application?](http://stackoverflow.com/q/1399008/299327). – Ryan Gates Dec 10 '12 at 22:27

5 Answers5

8

Have you tried

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

That should do the trick.

Marcus
  • 5,987
  • 3
  • 27
  • 40
5
public string FullPathRelativeTo(string root, string partialPath)
{
    string oldRoot = Directory.GetCurrentDirectory();
    try {
        Directory.SetCurrentDirectory(root);
        return Path.GetFullPath(partialPath);
    }
    finally {
        Directory.SetCurrentDirectory(oldRoot);
    }
}
plinth
  • 48,267
  • 11
  • 78
  • 120
4

If you're currently in c:\test and you want to get c:\MyOtherFolder\foo.bar without knowing that you're in c:\test you want to do;

 Environment.CurrentDirectory = @"..\MyOtherFolder"; //navigation accepts relative path
 string fullPath = Directory.GetCurrentDirectory(); // returns full path

After that you may want to set the current directory back to your previous location.

Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
3

You can do

new DirectoryInfo( @"..\MyOtherFolder\foo.bar" ).FullName
2

Try to use Path.Combine(...) method, it has to help you to achieve what you want..

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    I get the impression the OP is assuming he doesn't know that he's in `c:\tests`, he could be anywhere, and wants to get a full path given a relative path so `Path.Combine` will not work. – evanmcdonnal Dec 10 '12 at 21:36