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?
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");
使用:
System.IO.Path.GetFullPath(@"..\..\Project2\xml\File.xml")
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
Please note that using Path.Combine() might not give you the expected result, eg:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.