Wednesday, February 13, 2008

App.config in C# with VS2005 - Part I: EXE

Using the app.config has been giving me a few headaches. And googling it has revealed many others have the same kind of problems! So here is an overview of how it works:

From a Windows form project (mine is called TestAppConfig), you can add the app.config setting by right-clicking on the project, selecting "properties" and then choosing the "settings" tab. Add an "Application" setting into the settings designer (eg "MyVal") and you will find an "app.config" file has been added to your project. It will contain something like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" >
<section
name="TestAppConfig.Properties.Settings"
type="System.Configuration.ClientSettingsSection,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<TestAppConfig.Properties.Settings>
<setting name="MyVal" serializeAs="String">
<value>15</value>
</setting>
</TestAppConfig.Properties.Settings>
</applicationSettings>
</configuration>


From your code, you can access this setting like this:

string myval = 
TestAppConfig.Properties.Settings.Default.MyVal;


If you take where the code has been built (eg. ..\TestAppConfig\bin\Debug), you'll see that the app.config has been created using the name of your exe, in my case TestAppConfig.exe.config. If you run the exe from this folder it will use the value from this config file. If you change the value in the config it will be picked up the next time that the application is started - it does not pick it up changes immediately!


If you need to get the changed value picked up at run-time, you can use the reset method:

TestAppConfig.Properties.Settings.Default.Reset();

No comments: