获取文件的相对路径?路径、文件

2023-09-07 16:28:05 作者:4.桃语洵川.

我已经找到了一个叫settings.xml文件:

I have a file called settings.xml located at:

C:\解决方法1 \解决方法1 \ DATA \的settings.xml

现在,我做的:

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

请注意经常提示

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.

您可以使用

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");

请注意,在Windows Vista和更高版本,你不会有写的访问默认情况下位于您的安装目录下的目录。

Note that under Windows Vista and later, you will not have write access by default to a directory located under your install directory.