如何获取当前正在执行的DLL的位置? [英] How to get the location of the DLL currently executing?

查看:128
本文介绍了如何获取当前正在执行的DLL的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,我需要加载作为我正在写的一个dll的一部分。

I have a config file that I need to load as part of the execution of a dll I am writing.

我遇到的问题是我的地方当应用程序运行时,将dll和config文件放在当前位置中。

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

例如,我将dll和xml文件放在这里:

For example, I put the dll and xml file here:


D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

但是,如果我尝试引用xml文件(在我的DLL中),如下所示:

But if I try to reference the xml file (in my dll) like this:

XDocument doc = XDocument.Load(@".\AggregatorItems.xml")

然后 .\AggregatorItems.xml 转换为:


C:\windows\\ \\ system32\inetsrv\AggregatorItems.xml

C:\windows\system32\inetsrv\AggregatorItems.xml

所以,我需要找到一个方法(我希望)知道在哪里当前正在执行的位置。基本上我正在寻找:

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located. Basically I am looking for this:

XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")


推荐答案

您正在寻找 System.Reflection.Assembly.GetExecutingAssembly()

You are looking for System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");

修改:

显然,在某些情况下(<使用NUnit,TFS实例化的DLL,Outlook?)进行测试,位置属性无法正常工作 - 在这种情况下,您可以使用 CodeBase 属性。

Apparently the Location property does not work correctly under some conditions (testing using NUnit, TFS instantiated DLL, Outlook?) - in that case you can use the CodeBase property.

这篇关于如何获取当前正在执行的DLL的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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