leora
leora

Reputation: 196429

Concatenating Environment.CurrentDirectory with back path

If i have the following directory structure:

Project1/bin/debug
Project2/xml/file.xml

I am trying to refer to file.xml from Project1/bin/debug directory

I am essentially trying to do the following:

string path = Environment.CurrentDirectory + @"..\..\Project2\xml\File.xml":

what is the correct syntax for this?

Upvotes: 5

Views: 10878

Answers (4)

Blair Conrad
Blair Conrad

Reputation: 241714

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

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

Upvotes: 10

M4N
M4N

Reputation: 96541

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

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

This results in in the following string:

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

If you expect the path to be "c:\dir1\Project2\xml\File.xml", then you might use a method like this one instead 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);
}

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532445

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

One ".." takes you to bin

Next ".." takes you to Project1

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

Then down to the file

Upvotes: 2

lubos hasko
lubos hasko

Reputation: 25052

Use:

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

Upvotes: 4

Related Questions