如何获取当前正在执行的DLL的位置?

我有一个configuration文件,我需要加载作为我写一个DLL的执行的一部分。

我遇到的问题是,当应用程序运行时,我放置dll和configuration文件的位置不是“当前位置”。

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

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

但是,如果我尝试引用xml文件(在我的dll中),像这样:

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

那么\ AggregatorItems.xml转换为:

C:\ WINDOWS \ SYSTEM32 \ INETSRV \ AggregatorItems.xml

所以,我需要find一种方法(我希望)知道当前正在执行的DLL位于何处。 基本上我正在寻找这个:

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

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

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

编辑:

显然Location属性在某些情况下不能正常工作(使用NUnit,TFS实例化的DLL,Outlook?testing) – 在这种情况下,您可以使用CodeBase属性。

正如已经指出的,reflection是你的朋友。 但是你需要使用正确的方法;

 Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process. Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called. Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined. 

在我的情况下(处理我的程序集加载[作为文件]到Outlook):

 typeof(OneOfMyTypes).Assembly.CodeBase 

请注意在程序集上使用CodeBase (而不是Location )。 其他人则指出了find这个组件的另一种方法。

 System.Reflection.Assembly.GetExecutingAssembly().Location 

如果您使用的是asp.net应用程序,并且在使用debugging程序时想查找程序集,则通常会将其放入临时目录中。 我写了这个方法来帮助那个场景。

 private string[] GetAssembly(string[] assemblyNames) { string [] locations = new string[assemblyNames.Length]; for (int loop = 0; loop <= assemblyNames.Length - 1; loop++) { locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault(); } return locations; } 

欲了解更多详情,请参阅此博客http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

如果您无法更改源代码或重新部署,但可以使用Process Explorer检查计算机上正在运行的进程。 我在这里写了一个详细的描述[当开发人员可以改变代码以包含所需的代码片段时,所有build议的答案都可以工作,但是如果您想在不更改任何代码的情况下执行此操作,则可以使用Process Explorer。

它会列出系统上所有正在执行的DLL,您可能需要确定正在运行的应用程序的进程ID,但通常不会太困难。

我已经写了一个完整的描述,如何做到这一点在一个DLL里面二 – http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web服务器/ 在这里input链接描述