[ACCEPTED]-Concatenating Environment.CurrentDirectory with back path -path

Accepted answer
Score: 10

It's probably better to manipulate path 2 components as path components, rather than 1 strings:

string path = System.IO.Path.Combine(Environment.CurrentDirectory, 
                                     @"..\..\..\Project2\xml\File.xml");
Score: 4

Use:

System.IO.Path.GetFullPath(@"..\..\Project2\xml\File.xml")

0

Score: 2
string path = Path.Combine( Environment.CurrentDirectory,
                            @"..\..\..\Project2\xml\File.xml" );

One ".." takes you to bin

Next ".." takes 2 you to Project1

Next ".." takes you to Project1's 1 parent

Then down to the file

Score: 1

Please note that using Path.Combine() might 5 not give you the expected result, e.g:

string path = System.IO.Path.Combine(@"c:\dir1\dir2",
                                     @"..\..\Project2\xml\File.xml");

This 4 results in in the following string:

@"c:\dir1\dir2\dir3\..\..\Project2\xml\File.xml"

If you 3 expect the path to be "c:\dir1\Project2\xml\File.xml", then 2 you might use a method like this one instead 1 of Path.Combine():

public static string CombinePaths(string rootPath, string relativePath)
{
    DirectoryInfo dir = new DirectoryInfo(rootPath);
    while (relativePath.StartsWith("..\\"))
    {
        dir = dir.Parent;
        relativePath = relativePath.Substring(3);
    }
    return Path.Combine(dir.FullName, relativePath);
}

More Related questions