获取参考方法的装配位置

时间:2017-03-21 15:51:38

标签: c# dll configuration mapping .net-assembly

我有一个主应用程序引用的DLL。当我从DLL调用方法时,我需要从特定于DLL的app.config文件中读取配置。但是,当我将Configuration Manager映射到所需的配置文件时,我注意到GetExecutingAssembly()返回主应用程序的程序集而不是引用的DLL。有没有办法在使用DLL时获得精确的DLL程序集位置?当然,我想更新我的DLL,以便它在执行时总是返回自己的assebmlylocation。

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = Assembly.GetExecutingAssembly().Location);
Configuration libConfig = ConfigurationManager.OpenMappedExeConfiguration(
       map, ConfigurationUserLevel.None);

2 个答案:

答案 0 :(得分:0)

您需要使用Reflection来获取它。有一个方法GetAssembly返回包含传递类型的程序集。

示例:

string s = Assembly.GetAssembly(typeof(MemoryStream)).CodeBase;

返回mscorlib.dll的路径:

“文件:/// C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll”

答案 1 :(得分:0)

为什么需要程序集的配置文件?通常你要做的是配置 apps ,而不是 libraries 。因此,程序A的用户可能具有这些设置,而程序B的用户具有这些设置,但两个程序可能使用相同的引用程序集。

无论如何,如果您真的需要这样做,您可以使用MethodBase.GetCurrentMethod()获取您当前使用的引用程序集的位置:

string assemblyPath = MethodBase.GetCurrentMethod().DeclaringType.Assembly.Location;
Configuration libConfig = ConfigurationManager.OpenExeConfiguration(
   assemblyPath);
相关问题