Multiple App.Config Files in .NET Class library project

后端 未结 3 1439
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 07:20

I am creating one class library project. Now by default I have one App.Config file so that I am putting all environment specific data in that Config file.

Now based

相关标签:
3条回答
  • 2020-12-05 07:50

    The app will use the config file named YourExcecutable.exe.config which is by default the file App.config included in your (executable) project. Note, that .NET only loads one config file for the whole application. You cannot use multiple configuration files (i.e. one per library project) without coding.

    1. Option: You can use postbuild events and different solution configurations to copy one or another App.Config file to the output folder

    2. Option: You can use the ConfigurationManager Class to load an alternate config file by code.

    0 讨论(0)
  • 2020-12-05 07:59

    Now there is an even better solution: SlowCheetah - XML Transforms

    0 讨论(0)
  • 2020-12-05 08:05

    Loading a different application configuration file at run time can be done using mapped configuration file. You need to add reference to System.Configuration.dll in your project.

    Set the value of Copy to Output Directory property of all the additional config files (e.g. App1.config, App2.config etc.) other than the default one (App.config) to Copy if newer. This way they will be available in the project output directory (\bin\debug) after the project has been built. Default value of this property is Do not copy.

    Here is the code snippet on how to read configuration data from non-default config files:

    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
    configFileMap.ExeConfigFilename = "App1.config"; // app1.config should be present in root directory from where application exe is kicked off
    
     // Get the mapped configuration file
     var config = ConfigurationManager.OpenMappedExeConfiguration( 
            configFileMap, ConfigurationUserLevel.None);
    
     //get the relevant section from the config object
    AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
    
    //get key value pair
    var keyValueConfigElement = section.Settings["appSettingsKey"];
    var appSettingsValue = keyValueConfigElement.Value;
    

    If you have multiple app configuration files then you can keep a setting in default App.config file with the help of which you can make a decision at run time about which additional config file to load e.g. App1.config

    Note: Be aware that the code like ConfigurationManager.AppSettings["DeployEnv"] will still read the data from the default App.config file. This behavior can't be changed. Loading of default App.config file can't be prohibited. You have to use alternate means as shown above to read the data from non-default configuration files

    0 讨论(0)
提交回复
热议问题