如果我有以下目录结构:
Project1/bin/debug
Project2/xml/file.xml
我正在尝试从 Project1/bin/debug 目录中引用 file.xml
我基本上是在尝试执行以下操作:
string path = Environment.CurrentDirectory + @"..\..\Project2\xml\File.xml":
什么是正确的语法?
将路径组件作为路径组件而不是字符串来操作可能会更好:
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" );
一“..”带你去bin
下一个“..”带你到 Project1
下一个“..”将您带到 Project1 的父级
然后下到文件
请注意,使用 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);
}