Monday, March 1, 2010

How to use the app.config file in VS.NET 2008

I know this is straight forward, but for some reason I wasn't able to figure it out at first.  Can't remember what I did wrong, but here is how you can use it:

- Right click on the project and go to Properties.  Click on the settings tab.  In this area start typing in values.  At first there might be a little lag, as the IDE will create a file called app.config, and another one called Settings.settings and Settings.Designer.cs (under the properties folder).  Once you are done you can specify the type of setting, the scope (application, user) and a default value.

The way you access them is such:
Properties.Settings.Default.<Name of Property>.  For example, "Properties.Settings.Default.Username"

The way you set values to this property is such:
Properties.Settings.Default.<Name of Setting> = Value;
Properties.Settings.Default.Save();

That's it. 

I was working in WPF and I wanted to access a setting in the App.xaml.cs file.  However for some reason Properties.Settings wasn't showing up on IntelliSense.  It turns out to be some namespace issue.  In the file app.config my settings are under the following block:
<MainNameSpace.ApplicationName.Properties.Settings> (I changed MainNameSpace and ApplicationName, but your file will have something similar).
The way I was able to access those settings was via:
Noblis.EBTSFileManager.Properties.Settings.Default.<Name of Setting>

Another thing I thought I needed to do was to include the app.config file in the bin directory.  This is not necessary.  The file is copied to the output directory via the application name.  so it will be something like: MainNameSpace.ApplicationName.exe.config.  Ther is also another file there called MainNameSpace.ApplicationName.vshost.exe.config.

More information can be found here:
http://msdn.microsoft.com/en-us/library/a65txexh(VS.80).aspx
http://msdn.microsoft.com/en-us/library/bb397755.aspx

One thing I need to figure out is where is the file with the settings.  For example, I keep a default username in my settings file.  When I run the application, it seems to be loading the values from the file, but the MainNameSpace.ApplicationName.exe.config doesn't have the default username, it looks just like the app.config file.  Where does it go?

No comments: