获取程序集正在执行的目录的最佳方式是什么? [英] What's the best way to get the directory from which an assembly is executing

查看:92
本文介绍了获取程序集正在执行的目录的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我将一些配置文件与程序集(exe)一起存储在xml中,还有一些其他用于处理目的的临时文件。

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

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

我一直在使用

String configPath = ".\\config.xml";

它工作正常,直到我调用 OpenFIleDialog 打开其他文件夹中的一些文件,上面的语句失败。显然.\是指CurrentDirectory,当我们浏览到另一个文件夹时,它会更改。

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.

在某些时候,我使用

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

在某些时候,当我需要使用 Process.Start(),事情开始分崩离析。显然,工作目录设置不正确,而且我认为 Application.StartupPath 实际上是指工作目录而不是组件正在执行的目录。所以我不得不诉诸于使用ProcessInfo来设置工作目录到程序集的目录。我在编写VSTO时也遇到了这个问题。

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?

编辑:我的目的是获取该程序集所在的目录

I meant to get the directory which the assembly reside

编辑:根据MSDN在 AppDomain.BaseDirectory ,它似乎可以在运行时更改,这是我不想要的(只是为了澄清,不是我不想允许更改BaseDirectory,而是当我检索它不知道是否被改变)

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)

编辑:我注意到一个相关的问题发布得更早了。 什么会导致当前目录执行应用程序更改?

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

感谢你们的答案。

推荐答案

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

这篇关于获取程序集正在执行的目录的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆