Getting relative path of file?

我怕爱的太早我们不能终老 提交于 2019-12-24 11:22:05

问题


I have a file called settings.xml located at:

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.


回答1:


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 e.g. 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.




回答2:


You can also get relative to the current directory it was started from

System.Environment.CurrentDirectory


来源:https://stackoverflow.com/questions/12698599/getting-relative-path-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!