什么是获取从中组件正在执行的目录中的最佳方式组件、方式、目录中

2023-09-02 21:44:30 作者:执手问年华

有关我的应用程序,我存储在XML中的一些配置文件以及组件(EXE),以及一些其他临时文件等待处理的目的。

我发现了一些怪癖。\ Application.StartupPath

我一直在使用

 字符串configPath来=\ config.xml中。
 

它正常工作,直到我叫打开文件对话框来打开其他文件夹中的一些文件,上面失败的声明。显然。指的是currentDirectory所,从而改变每次当我们浏览到另一个文件夹。

在某一点上,我是用

 字符串configPath来= Path.Combine(Application.StartupPath +config.xml文件);
 
什么是OpenStack OpenStack核心组件之运行流程

在某些时候,当我需要使用的Process.Start从另一个文件夹执行此组件(),事情开始土崩瓦解。显然,工作目录设置不正确,而 Application.StartupPath 实际上是指工作,而不是它的组件执行目录的目录,因为我认为。所以,我不得不求助于使用ProcessInfo设置工作目录到装配的目录。我也有问题,当我在写VSTO。

所以,我的问题是,什么是让该组件执行,如果没有这些怪癖(或误解)当前目录是我刚才提到的最好,最简单,最放心的方式?

编辑:我的意思是让该组件所在的目录

编辑:根据MSDN上的AppDomain.BaseDirectory,它似乎可以运行,这是我不希望(只是为了澄清,不是我不想让改变BaseDirectory,而是当我找回它不知道肯定是否已被改变时改变)

编辑:我注意到一个相关的问题是更早公布。 What会导致执行应用程序的当前目录改变?

谢谢你们的回答。

解决方案

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))

For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose.

I found some quirk with ".\" and Application.StartupPath.

I've been using

String configPath = ".\config.xml";

It works fine until I called OpenFIleDialog to open some files in other folders, the statement above failed. Apparently "." is referring to "CurrentDirectory", which changes every time when we browse to another folder.

At some point, I was using

String configPath = Path.Combine(Application.StartupPath + "config.xml");

At some point, when I need to execute this assembly from another folder by using Process.Start(), things start to fall apart. Apparently the working directory is not set properly, and Application.StartupPath is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO.

So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned?

EDIT: I meant to get the directory which the assembly reside

EDIT: According to MSDN on AppDomain.BaseDirectory, it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed)

EDIT: I've notice that a related question was posted much earlier. What would cause the current directory of an executing app to change?

Thanks guys for the answer.

解决方案

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))