C# – How to use custom configuration file or app.config in .NET application

app-configcconfigurationconfiguration-filesnet

I have MVC5 .NET 4.6.1 C# web application
I want to create a custom config file separate from web.config to store some settings my application uses.

I tried to follow this article https://support.microsoft.com/en-us/kb/815786

however the items I set in app.config:

<?xml version="1.0"?>
<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.6.1" />
      <httpRuntime targetFramework="4.6.1" />
    </system.web>
  <appSettings>
      <add key="Key0" value="0" />
      <add key="Key1" value="1" />
      <add key="Key2" value="2" />
   </appSettings>

</configuration>

are not seen in my application see , eg. they come as null:

string attr = ConfigurationManager.AppSettings["Key0"];

Why isn't it working? Am I missing something?

Alternatively I would like to create a custom config file eg. mycustom.config to define my global app settings.

EDIT

Solution I used

Follwing this post https://social.msdn.microsoft.com/Forums/vstudio/en-US/11e6d326-c32c-46b1-a9a2-1fbef96f33ee/howto-custom-configuration-files?forum=netfxbcl

In web.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
       <configSections>
              <section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
       </configSections>
       <newAppSettings file="C:\mycustom.config"/>
</configuration>

Then mycustom.config

<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
       <add key="OurKey" value="OurValue"/>
</newAppSettings>

And reading the value:

System.Collections.Specialized.NameValueCollection newAppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings");
string key = Convert.ToDateTime(newAppSettings["OurKey"]);

Best Answer

You can use separate config file for connection strings and app settings:

<appSettings configSource="appSettings.config" />
<connectionStrings configSource="connectionStrings.config"/>

appSettings.config file

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
    <add key="Setting1" value="App setting 1" />
</appSettings>

connectionStrings.config file

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
    <add name="MyConnStr1" connectionString="My connection string" />
</connectionStrings>

Usage is same as it was before:

var setting1 = ConfigurationManager.AppSettings["Setting1"];
var connString1 = ConfigurationManager.ConnectionStrings["MyConnStr1"].ConnectionString;