dan*_*man 4 c# path relative-path filepath
我目前正在用C#在Visual Studio中编写一个项目。该项目的完整路径是:
"C:\TFS\MySolution\"
Run Code Online (Sandbox Code Playgroud)
我有一个在执行过程中需要加载的文件。可以说文件路径是
"C:\TFS\MySolution\Project1\NeedtoLoad.xml"
Run Code Online (Sandbox Code Playgroud)
我不想编写硬编码的完整路径,并且想要以动态方式获取路径。
我使用以下行:
var path = Directory.GetCurrentDirectory();
Run Code Online (Sandbox Code Playgroud)
我找到的每个方法以及上面的代码行都为我提供了以下路径的问题:
"C:\TFS\MySolution\Project1\bin\Debug"
Run Code Online (Sandbox Code Playgroud)
我需要的是
"C:\TFS\MySolution\Project1\"
Run Code Online (Sandbox Code Playgroud)
所以我可以串联
NeedtoLoad.xml
Run Code Online (Sandbox Code Playgroud)
答案。
我当然可以:
path.Substring(0, path.IndexOf("bin\\Debug"));
Run Code Online (Sandbox Code Playgroud)
但这不是那么优雅。
您可以使用Directory.GetParent及其Parent成员
string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
Run Code Online (Sandbox Code Playgroud)
将向上升级路径树并返回"C:\TFS\MySolution\Project1"。