Click here to Skip to main content
15,881,712 members
Articles / Programming Languages / Visual Basic

Loading settings from config file

Rate me:
Please Sign up or sign in to vote.
4.89/5 (10 votes)
10 May 2012CPOL3 min read 74.2K   2.9K   24   12
How to load settings from app.config without recompiling the code.

Introduction

This article shows how to load application settings from a config file without recompiling the code in Visual Studio. This feature is provided by .NET automatically if your project is a single EXE. However, when I tried to do the same with DLL, this feature didn't work for me, the config file was not loading when the application started. There are many related articles, but I couldn't find a ready-for-use solution. Therefore, I've decided to take a time and contribute this article.  I hope it will be useful for some folks like myself... 

Background  

Recently, I've been working on a plug-in (DLL) which required high level of configurability, on both user and application levels. My first choice was to utilize the app.config mechanism provided by the .NET framework. With this mechanism, application and user settings can be conveniently defined in the Visual Studio front end. And these settings are immediately available in the code through My.Settings object. Moreover, the system automatically creates a config file which is stored with the binaries. If My.Settings needs to be updated it should be possible with the Reload() method. So far, so good...    Unfortunately, I've found that the config file  is NOT loaded when the application starts. It means that if the user modifies the config file manually, the new values are not reflected. In order to change the config settings the user would have to use the Visual Studio and then recompile the code! Frown | <img src=. So, if we'd like to re-distribute new config file among large number of users/machines, the new settings would NOT be used. I couldn't believe that this is the right behavior for people at Microsoft, so I started looking for a solution. After spending some time on searching for a solution, I decided to write my own code to re-load setting values from the config file provided by .NET. 

Using the code 

To demonstrate the concept, I've created a small test application in VB.NET. The application loads settings from the config file and shows them as a property grid.  As shown in bellow: 

Image 2

 The user can open config file for editing through File->Edit, modify settings in his favorite editor and then reload these values into the application using File->Reload.  

 Image 3

 



The implementation of the config file parser is provided in the SettingsHelper.vb module.  One has to start from retrieving the config file handle.   

VB.NET
Dim config = ConfigurationManager.OpenExeConfiguration(My.Application.Info.AssemblyName + ".exe")

Sections of the config file can be accessed as follows: 

VB.NET
Dim settingsSection As ClientSettingsSection = config.GetSection(sectionName)

 Then, each setting needs to be copied and converted from string to  it's actual type. This type can be  recovered from the My.Settings item.

VB.NET
For Each st As SettingElement In settingsSection.Settings

           'get setting name and value
           Dim name As String = st.Name
           Dim value As String = st.Value.ValueXml.InnerText

           'skip unknown settings
           Dim mySettingsItem = My.Settings.Item(name)
           If mySettingsItem Is Nothing Then
               Continue For
           End If

           'get setting type
           Dim itemType = mySettingsItem.GetType

           'check setting type name
           'some types require special treatment
           If itemType.Name = "StringCollection" Then

               mySettingsItem.Clear()

               'populate new string collection
               Dim arrayOfString = st.Value.ValueXml.SelectNodes("ArrayOfString/string")
               For i = 0 To arrayOfString.Count - 1
                   Dim newString = arrayOfString.Item(i).InnerText
                   mySettingsItem.Add(newString)
               Next

           ElseIf itemType.Name = "Color" Then
               If value.Contains(",") Then
                   Dim rgbValues As String() = value.Split(",")
                   Dim r As Integer = Convert.ToInt32(rgbValues(0))
                   Dim g As Integer = Convert.ToInt32(rgbValues(1))
                   Dim b As Integer = Convert.ToInt32(rgbValues(2))
                   mySettingsItem = Color.FromArgb(r, g, b)
               Else
                   mySettingsItem = Color.FromName(value)
               End If
           Else

               'try to cast
               Try
                   mySettingsItem = CTypeDynamic(value, itemType)
               Catch ex As Exception
                   MsgBox("Cannot read " + name + " from config file!", MsgBoxStyle.Critical)
                   Continue For
               End Try

           End If

           'update My.Settings
           My.Settings.Item(name) = mySettingsItem
       Next

Please notice, that certain types cannot be casted directly and require special treatment. In the current example, we handle StringCollection and Color, which are the most commonly used. However, you may need to extend this code in order to handle more complex types. Once the item value has been successfully retrieved it is set back into the My.Settings object.  

Points of Interest 

It is important to remember, that the original app.config file created by Visual Studio is copied into the Bin directory once the code is compiled. Depends on your case, you may not want to override the USER settings, but only the APPLICATION settings. User settings allow customization of the application behavior for each user, so the values for these settings are stored separately. 





License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Gun Gun Febrianza17-Aug-12 13:49
Gun Gun Febrianza17-Aug-12 13:49 
Questionnot bad Pin
BillW336-Jun-12 10:27
professionalBillW336-Jun-12 10:27 
GeneralMy vote of 3 Pin
frankazoid13-May-12 3:12
frankazoid13-May-12 3:12 
Question[My vote of 2] You can combine the assembly-level configurations into the exe config file. Pin
frankazoid11-May-12 9:21
frankazoid11-May-12 9:21 
AnswerRe: [My vote of 2] You can combine the assembly-level configurations into the exe config file. Pin
sergaz11-May-12 9:42
sergaz11-May-12 9:42 
GeneralRe: [My vote of 2] You can combine the assembly-level configurations into the exe config file. Pin
frankazoid13-May-12 3:11
frankazoid13-May-12 3:11 
GeneralRe: [My vote of 2] You can combine the assembly-level configurations into the exe config file. Pin
sergaz14-May-12 4:50
sergaz14-May-12 4:50 
QuestionAre you sure about the config file not being loaded? Pin
John Brett11-May-12 0:18
John Brett11-May-12 0:18 
AnswerRe: Are you sure about the config file not being loaded? Pin
sergaz11-May-12 5:56
sergaz11-May-12 5:56 
GeneralRe: Are you sure about the config file not being loaded? Pin
John Brett11-May-12 6:02
John Brett11-May-12 6:02 
GeneralRe: Are you sure about the config file not being loaded? Pin
sergaz11-May-12 6:27
sergaz11-May-12 6:27 
GeneralRe: Are you sure about the config file not being loaded? Pin
Juan Pablo G.C.11-May-12 6:27
Juan Pablo G.C.11-May-12 6:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.