shearichard
shearichard

Reputation: 8362

C# console app can't read auxiliary App.config

I have a C# console app. It reads values from App.config.

Within App.config I make use of the file property of the appSettingssection.

In this way I can have a secondary configuration file that should supplement/overwrite properties defined in the primary configuration file.

However I find that the properties in the secondary file are not available at run time.

App.config (extract)

<appSettings file="App-not-in-source-control.config">
    <add key="THIS_IS_A_TEST_KEY" value="Test Value" />
      ....        
</appSettings>

App-not-in-source-control.config

<appSettings>   
    <add key="SOMEVALUE" value="foobar"/> 
</appSettings>

Program.cs (Extract)

//THIS WORKS
var only4dbg = ConfigurationManager.AppSettings["THIS_IS_A_TEST_KEY"].ToString();
//THIS DOESNT WORK
var someValue = ConfigurationManager.AppSettings["SOMEVALUE"].ToString();

The attempt to read SOMEVALUE results in the following exception

Unhandled Exception: System.NullReferenceException: 
Object reference not set to an instance of an object.

Is there something I've overlooked here ?

Upvotes: 1

Views: 1008

Answers (1)

shearichard
shearichard

Reputation: 8362

OK well having written that all out I realised what the problem was.

The secondary config file is only available to the run time if you've set the 'Copy to Output Directory' property of the file to something other than 'Never' ('Never' is the default setting).

It's strange to me that 'Never' is the default setting ; it's not the case for the 'App.config' and the secondary config (at least in my case) was created using the 'Add | New Item | Application Configuration File' dialog sequence within 'Solution Explorer' - there doesn't seem to be much point asking Visual Studio to create a config file which isn't going to be available to the project build output.

Regardless that's the way it is - hope this helps someone else.

Upvotes: 3

Related Questions