简体   繁体   English

C#中的多个配置文件

[英]multiple config file in c#

I have a solution containing 1 console application and 2 libraries. 我有一个包含1个控制台应用程序和2个库的解决方案。

In the libraries I have two different app.configs for an example my data.config 在库中,我有两个不同的app.configs作为示例我的data.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="OutputFileFolder" value="c:\\log" />
    <add key="OutputIndexFile" value="c:\\log\index.xml" />
  </appSettings>
</configuration>

And in this library class I have in the constructor 在这个库类中,我在构造函数中

_indexPath = ConfigurationManager.AppSettings["OutputIndexFile"]; 

But how should I load the Data.config file from my main console application (this should be the main config file)? 但是我应该如何从主控制台应用程序加载Data.config文件(这应该是主配置文件)?

Config files in your dll projects are not relevant at runtime. dll项目中的配置文件在运行时不相关。 The config file (if any) in your console application project is the one that will get used. 控制台应用程序项目中的配置文件(如果有)将被使用。

If you want to use a configuration file in two separate projects, you can add it as a link to your second project, or you could use a post-build event to copy it over. 如果要在两个单独的项目中使用配置文件,可以将其添加第二个项目的链接 ,也可以使用构建后事件将其复制过来。 However both of these seem a little hacky. 但是,这两者似乎都有些古怪。

Libraries don't really have associated configuration files as such - they operate under an executable (a console application, in your case). 库实际上没有关联的配置文件,它们在可执行文件(在您的情况下为控制台应用程序)下运行。

You should put all the configuration in the app.config file of the application for the code in the libraries to have access to it. 您应该将所有配置都放在应用程序的app.config文件中,以便库中的代码可以访问它。

You can load multiple config files by have multiple Configuration instances from multiple calls to ConfigurationManager.OpenMappedExeConfiguration (add your config file to the file map, the global file will be added automatically and specify a ConfigurationUserLevel.None . 通过有多个可以加载多个配置文件Configuration多个调用实例ConfigurationManager.OpenMappedExeConfiguration (添加您的配置文件到文件的地图,全球文件将被自动添加,并指定一个ConfigurationUserLevel.None

Something like: 就像是:

var fileMap = new ExeConfigurationFileMap {
                    ExeConfigFilename = Path of dll's config file
             };

var cfg = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var result = cfg.AppSettings["OutputIndexFile"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM