1. Introduction to AppConfig File
Let us say we are writing an Internet modem device monitor service application. The duty of the application will be tracking for Upload and download action of the modem. When there is a large download say 500KB per second for past 10 Minutes, the device should assert that to a user. The intimation can be done either by blinking a Red LED in the modem device or by making continues beep or by making the entire desktop with a red transparent overlay. But which option the utility should choose from? Now I hear you are saying keep it as an ‘Application Setting’. In C#, it is AppConfig file.
In old days, Legacy windows desktop software uses section-based Initialization Config Files (‘INI Files’) and App reads and writes from it. The coder places the settings on sections, which are nothing but organizing the settings under a certain group. Now in dot net days, Microsoft replaced the INI files as AppConfig files. They place the App settings in the XML format in application config files aka AppConfig file. In this article, we will explore how to make use of the AppConfig file. For exploring, we will create a simple C# Windows Form based example.
2. Config File Hierarchy
The config file has a hierarchy and the application will search for required settings based on this. Have a look at the below picture:
The first thing to be noted is that Web Application looks for settings in the ‘web.Config’ whereas windows desktop application will look for the settings in the ‘App.Config’ file. Let us say a web server machine Johns-Kitten is hosting three websites . Also we assume that all three websites are from the same publisher. Now the settings common to all three websites goes to ‘Root.Web.Config’ and settings specific to one website or solution goes to the ‘web.config file’.
The settings, which are common to both web app and desktop app, can go in ‘Machine.config’ File. The settings defined in the bottom-most overrides, the settings given in the above level. For example, the settings given in the web.config overrides the settings given in the ‘Machine.Config’ file (i.e.) if the same setting is defined in both the machine.config and web.config, web.config setting takes the precedence. In this article, we will explore how to use the App.Config file in desktop C# windows applications.
3. About AppConfig C# Example
Have a look at the below application screen shot:
Clicking the ‘Application Setting’ button marked in the picture (as 4) will fetch the application settings from the App.config file and shows that in the Display Output (Marked as 1). A key will point out the setting that needs to be fetched and it will be typed in the text box marked as 3. Clicking the button “Get Connection string” (Marked as 2) will fetch the connection string set in the app.config file and shows that in the display output. Specifying the name of the connection string will retrieve the connection string. In our sample, connection string name set in the App.config file is referred by the check boxes marked as 5 in the screenshot.
This example will help us to do the following tasks:
- Create App.Config file for the projects.
- Define the settings inside this AppConfig file.
- Read Settings from different Section of the Config file.
4. Assembly Reference
First, we create Windows C# App called ReadConStr. After making the project, we can store all the App settings for this ReadConStr.exe into a config file called App.Config and read the settings from it through the ‘system.configuration’ assembly. The steps are below:
- Open the Solution Explorer
- Right Click the Reference node
- Click on the ‘Add Reference…’ menu item from the context menu.
This will display an ‘Add Reference’ dialog. We can pick the ‘System.Configuration’ assembly from this dialog as shown in the below screenshot. Once we pick the ‘System.Configuration’ from the ‘add reference’ dialog, the reference is added to the project and we can check that by drilling down the reference node.
After adding the reference, we can add the using statement to make use of the application configuration file:
1 2 |
//Sample 01: Required Config Entries using System.Configuration; |
5. Adding AppConfig File
Our Example Project is ready to read config settings and where is the config file? We should add this it to our application. To add the AppConfig file to the project, follow the steps listed below:
- Go to ‘Solution Explorer’
- Right click the project name ‘ReadConStr’ and chose ‘Add⇒New Item…’
- In the ‘Add New Item’ dialog, select the option, ‘Application Configuration File’ and leave the default name ‘App.Config’ as it is. And click on the ‘Add’ button. This will add the application configuration file to our project.
Once the config file (App.config) is added to our project, we can place our application wide project settings into this file. To add the App settings, we should open the app.config file from the solution explorer and add the below code:
The project keeps all the App specific settings inside the AppSettings tag. The setting goes with a ‘Key-Value’ pair. For example, the application will ask for the setting by giving the key say ‘Key_4’ and gets the setting value say, Value_4. Like application settings, Connection string holds a separate section as shown below:
In the above case, we enclose the database connection strings between ConnectionStrings tags. The application throws the ‘name’ and fetches the connection string and/or Provider details. In the above example, by knowing the name ‘XYZ1’, we can get connection string ‘XYZ2’ and Provider name ‘XYZ3’. If you are not expertise in the connection string, watch the below video to place connection string in your App.Config file:
Video 1: Creating ConnectionString in App.Config File
6. Reading Application Settings From AppConfig File
The event handler for the ‘Application Setting’ button is below:
1 2 3 4 5 6 7 8 |
//Sample 02: Read Application settings private void btnAppSettings_Click(object sender, EventArgs e) { string setting = ConfigurationManager.AppSettings[txtKey.Text]; if (setting == null) setting = "Setting not found"; txtDisplayOutput.Text = setting; } |
The ConfigurationManager Class holds the maps of
AppSettings
&
ConnectionStrings
. In the below event handler, we refer to the AppSettings map and get the needed setting value by supplying the key. We can mention the key in the text box, which is marked as 3 in the application screenshot. The click event handler will display the read value in the Result Display Area.
7. Reading ConnectionString from AppConfig File
In this section, we will read the Connection String setting from the AppConfig file. The for this is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//Sample 03: Read Connection String private void btnConString_Click(object sender, EventArgs e) { //3.1 Declarations ConnectionStringSettings setting_constr = null; string con_str = ""; //3.2 Get Connetion String for Pubs and/or NorthWnd if (chkPubs.Checked == true) { setting_constr = ConfigurationManager.ConnectionStrings["Pubs"]; con_str = setting_constr.ConnectionString + Environment.NewLine; } if (chkNWnd.Checked == true) { setting_constr = ConfigurationManager.ConnectionStrings["NWind"]; con_str = con_str + setting_constr.ConnectionString; } if (con_str == "") con_str = "Specify either Pubs or NWnd"; //3.3 Display the output txtDisplayOutput.Text = con_str; } |
The above code runs the when the user clicks the ‘Get Connection String’ button in the form. Here we refer the
ConnectionStrings
map from the
ConfigurationManager
object to get the
ConnectionStringSettings
object. This connection string map takes the name as the key. Look at our sample connection strings in the app.config; XYZ1 and abc1 are the key names for the connection strings. We fetch the actual connection string from the ConnectionStringSettings object using these keys. In our example, the handler code assigns the ConnectionStringSettings object into the variable
setting_constr
when the relevant checkbox is checked. The
ConnectionString
property from this
setting_constr
will be read to get actual connection string text. Once we have connection string setting, we show that in the display output.
8. Using AppConfig – Real Life Example
Now we will assign the fore color for the output display area using the AppConfig File. This setting shows a real-time example of how the config file will be used to change application behavior without re-compiling it. Have a look at the below code which reads the fore color setting from the AppConfig file and sets the multi-line text box’s fore-color based on the value read from it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//Sample 4: Application Background Color private void frmAppConfig_Load(object sender, EventArgs e) { //4.1: Read setting string ColorSetting = ConfigurationManager.AppSettings["FontColor"]; Color ForeColor; //4.2 Have a relevent Color if (ColorSetting == "Red") ForeColor = Color.Red; else if (ColorSetting == "Blue") ForeColor = Color.Blue; else ForeColor = Color.Green; //4.3 Assign it to the Text Display txtDisplayOutput.ForeColor = ForeColor; } |
We wrote the above code in the form load event handler. The code is like what you saw in section 6, but here we use the application setting to change the behavior of the text box. Or simply, the text display color of the text box will get changed based on the color setting given in the application configuration file. Note, you should add an entry under the App.Config file. The Video in the next section shows this entry.
9. Running the Application – Video
The below-given video shows how the example works with the application configuration file. This video also shows changing the behavior of the text box just by changing the configuration file.
Video 2: Running the Example
Source Code: Download AppConfig File Example From Google Drive
Categories: C#
Tags: AppSettings, ConfigurationManager, System.Configuration