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" ?>
<sectionGroup name="applicationSettings"
System, Version=, Culture=neutral,
PublicKeyToken=b77a5c561934e089" >
System, Version=, Culture=neutral,
requirePermission="false" />
<setting name="MyVal" serializeAs="String">

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

string 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:


No comments: