5

如果我有以下目录结构:

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

我正在尝试从 Project1/bin/debug 目录中引用 file.xml

我基本上是在尝试执行以下操作:

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

什么是正确的语法?

4

4 回答 4

10

将路径组件作为路径组件而不是字符串来操作可能会更好:

string path = System.IO.Path.Combine(Environment.CurrentDirectory, 
                                     @"..\..\..\Project2\xml\File.xml");
于 2008-12-06T12:56:23.477 回答
4

采用:

System.IO.Path.GetFullPath(@"..\..\Project2\xml\File.xml")
于 2008-12-06T12:56:21.637 回答
2
string path = Path.Combine( Environment.CurrentDirectory,
                            @"..\..\..\Project2\xml\File.xml" );

一“..”带你去bin

下一个“..”带你到 Project1

下一个“..”将您带到 Project1 的父级

然后下到文件

于 2008-12-06T12:56:57.517 回答
1

请注意,使用 Path.Combine() 可能不会给您预期的结果,例如:

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

这将产生以下字符串:

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

如果您希望路径是“c:\dir1\Project2\xml\File.xml”,那么您可以使用类似下面的方法而不是 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);
}
于 2008-12-06T13:17:45.603 回答