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

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

问题描述

对于我的应用程序,我将一些配置文件与程序集(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 有一些怪癖.

I found some quirk with ".\" and 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.

在某些时候,我正在使用

At some point, I was using

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

根据 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天全站免登陆