tags:

views:

693

answers:

4

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?

+1  A: 

Use:

System.IO.Path.GetFullPath(@"..\..\Project2\xml\File.xml")
lubos hasko
+4  A: 

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");
Blair Conrad
This translates to ..\Project1\bin\debug\..\..\Project2\... If you think about ".." just eating a previous directory in the path, you get ..\Project1\Project2\...
tvanfosson
True enough. I didn't count ak's ..'s - figured it was the lack of leading "\" that was doing them in. Will amend.
Blair Conrad
+2  A: 
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

tvanfosson
Actually, I prefer @lubos version, but with the correct path for the file.
tvanfosson
A: 

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);
}
M4N
But how about "..\" not at the beginning of relativePath? That's still a valid path. I would prefer to use System.IO.Path.GetFullPath to convert relative paths to absolute ones.
0xA3
<continued/>or using the DirectoryInfo and FileInfo classes might also be an option.
0xA3