views:

180

answers:

4

I'm looking for something akin to Path.Combine method that will help me correctly combine absolute and relative paths. For example, I want

Path.Combine(@"c:\alpha\beta", @"..\gamma");

to yield c:\alpha\gamma instead of c:\alpha\..\gamma as Path.Combine does. Is there any easy way of accomplishing this? Needless to say, I also want to period . path or multiple .. paths (e.g., ..\..\) to work correctly.

+3  A: 

You can probably do a Path.Combine followed by a Path.GetFullPath.

Moron
+5  A: 

Use Path.GetFullPath

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
Console.WriteLine(Path.GetFullPath(path));

or the DirectoryInfo class:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
DirectoryInfo info = new DirectoryInfo(path);
Console.WriteLine(info.FullName);

Both will output:

c:\alpha\gamma
Jason
Huh, didn't even know `GetFullPath` existed. Sexy.
Nick
+1  A: 

you could use a combination of 2 calls like so:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
string result = Path.GetFullPath(path);

And that should give you the results you're looking for.

Steve Danner
A: 

You can call Path.GetFullPath to resolve this.

For example, this code:

string path = Path.Combine(@"c:\alpha\beta", @"..\gamma");
Console.WriteLine(path); 
path = Path.GetFullPath(path);
Console.WriteLine(path);

Will print:

c:\alpha\beta\..\gamma
c:\alpha\gamma
Reed Copsey