简体   繁体   English

获取文件的相对路径?

[英]Getting relative path of file?

I have a file called settings.xml located at: 我有一个名为settings.xml的文件,位于:

c:\\solution1\\solution1\\data\\settings.xml

Right now, I am doing: 现在,我正在做:

XDocument doc = XDocument.Load(@"c:\solution1\solution1\settings.xml");

I can't figure how to do it with a relative path. 我不知道如何使用相对路径。

If you mean relative to your executable, you can use 如果您的意思是相对于可执行文件,则可以使用

string exeLocation = System.Reflection.Assembly.GetExecutingAssembly().CodeBase

Note the frequently suggested 注意经常建议

System.Reflection.Assembly.GetExecutingAssembly().Location

will get the path where the assembly is currently located , which can be different eg if a shadow copy is being executed. 将获取程序集当前所在的路径,该路径可以不同,例如,如果正在执行卷影副本。

You can use 您可以使用

string exeDir = System.IO.Path.GetDirectoryName(exeLocation);

to get the executable's directory. 获取可执行文件的目录。

If you want to find a file that is in a data directory under your install location, you could do 如果要在安装位置下的数据目录中找到文件,可以执行

string dataFile = Path.Combine(exeDir, "data\settings.xml");

Note that under Windows Vista and later, you will not have write access by default to a directory located under your install directory. 需要注意的是在Windows Vista和更高版本,你不会有默认的写访问位于你的安装目录下的目录。

您还可以相对于它从其开始的当前目录

System.Environment.CurrentDirectory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM