自定义配置部分:无法加载文件或程序集

ehc*_*ian 21 c# config

我在配置文件中尝试访问自定义配置部分非常困难.

正在从作为插件加载的.dll读取配置文件.我使用Configuration Section Designer VS addin 创建了配置和必要的代码.

命名空间是"ImportConfiguration".ConfigurationSection类是"ImportWorkflows".程序集是ImportEPDMAddin.

xml:

  <configSections>
    <section name="importWorkflows" type="ImportConfiguration.ImportWorkflows, ImportEPDMAddin"/>
  </configSections>
Run Code Online (Sandbox Code Playgroud)

每当我尝试读取配置时,我都会收到错误:

为importWorkflow创建配置节处理程序时出错:无法加载文件或程序集"ImportEPDMAddin.dll"或其依赖项之一.该系统找不到指定的文件.

dll不会与可执行文件驻留在同一目录中,因为加载插件的软件将dll和它的依赖项放在它自己的目录中.(我无法控制.)

我将单例实例的代码编辑为以下内容:

string path = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
path = path.Replace("file:///", "");
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(path);
return configuration.GetSection(ImportWorkflowsSectionName) as ImportConfiguration.ImportWorkflows;
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用一个简单的NameValueFileSectionHandler,但我得到一个例外,说它无法加载文件或程序集'System'.

我已经阅读了大量的博客文章和文章,听起来有可能为dll读取配置文件,但我无法让它工作.有任何想法吗?谢谢.

AJ.*_*AJ. 36

不幸的是,您需要将ImportEPDMAddin程序集与可执行文件驻留在同一文件夹中,驻留在与您正在使用的.Net框架相关的.Net框架文件夹中(即C:\ Windows\Microsoft.NET\Framework\v2) .0.50727),或在全球大会缓存中注册.

唯一的另一个选择是,如果你知道程序集的路径包含配置处理程序的定义类,你可以加载它而不需要像这样的引用:

//Class global
private Assembly configurationDefiningAssembly;

protected TConfig GetCustomConfig<TConfig>(string configDefiningAssemblyPath, 
    string configFilePath, string sectionName) where TConfig : ConfigurationSection
{
    AppDomain.CurrentDomain.AssemblyResolve += new 
        ResolveEventHandler(ConfigResolveEventHandler);
    configurationDefiningAssembly = Assembly.LoadFrom(configDefiningAssemblyPath);
    var exeFileMap = new ExeConfigurationFileMap();
    exeFileMap.ExeConfigFilename = configFilePath;
    var customConfig = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, 
        ConfigurationUserLevel.None);
    var returnConfig = customConfig.GetSection(sectionName) as TConfig;
    AppDomain.CurrentDomain.AssemblyResolve -= ConfigResolveEventHandler;
    return returnConfig;
}

protected Assembly ConfigResolveEventHandler(object sender, ResolveEventArgs args)
{
    return configurationDefiningAssembly;
}
Run Code Online (Sandbox Code Playgroud)

确保你处理AssemblyResolve事件,因为这将在没有它的情况下抛出异常.


小智 6

在主应用程序配置文件中,添加以下内容(其中插件是要从中加载程序集的文件夹.您可以使用分号分隔的多个路径.

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <probing privatePath=".;.\Plugins"/>
    </assemblyBinding>
</runtime>
Run Code Online (Sandbox Code Playgroud)

摘自http://msdn.microsoft.com/en-us/library/823z9h8w%28v=vs.90%29.aspx