Click here to Skip to main content
Click here to Skip to main content

How You Can Change the applicationSettings and userSettings Section of config File at Runtime.

, 25 Mar 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Allows you to edit the applicationSettings and userSettings section of config file
ReadConfigurationAppSettingSection

Disclaimer

I am not in any way involved in the administration of The Code Project, and the administrators have not, in any capacity, asked me to write this article. This article is completely based on my own personal views and experiences in programming and technical writing.  

Introduction

I searched on Google and did not find any exact results of resolving my problem “How can we change the applicationsettings values from a different project?” Finally I found something but there weren't many details available, so by adding some code I got how it can be done. This article shows how you can change the applicationsettings and usersettings section of config file at runtime. You can use it to create a project like Configuration Manager to manage multiple config files. You can also find an exciting resource on editing the appsetting key/value section at Edit and Encrypt Web.Config Sections Using C# 2.0.

Background

As per the MSDN - Application settings allow you to store and retrieve property settings and other information for your application dynamically, and they allow you to maintain custom application and user preferences on the client computer. You might want to store a user's color preferences, and then retrieve them the next time the application runs. Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString. The most common types are String, Integer, and Boolean, but you can also store values as Color, Object, or as a connection string. In Visual Basic projects, you can access application settings at run time using the My.Settings object. But I want to modify these settings by another project, so I have to write some custom code for accomplishing my task.

How the Application Runs

  1. When you run the source project, you get the following screen:

    Screen1

  2. Click the Load button, which loads the below settings in DataGridView:

    Screen2

  3. After changing the setting values:

    Screen3

  4. Click the Update button to update the changed values to config file.

Using the Code 

  1. Create a Web config file and add the following settings using the Solution->Property->Settings.
Screen4

See the app.config file now. The application settings are added.

Screen5
  1. Create a class named ConfigSettings as below:
    Public Class ConfigSettings
        Private _settingName As String
        Private _settingValue As String
        Private _serializeAs As String
    
        Public Property SettingName() As String
            Get
                Return _settingName
            End Get
            Set(ByVal value As String)
                _settingName = value
            End Set
        End Property
    
        Public Property SettingValue() As String
            Get
                Return _settingValue
            End Get
            Set(ByVal value As String)
                _settingValue = value
            End Set
        End Property
    
        Public Property SerializeAs() As String
            Get
                Return _serializeAs
            End Get
            Set(ByVal value As String)
                _serializeAs = value
            End Set
        End Property
    
    End Class
  2. Open the form and add the following controls:
    1. DataGridView and name it dgvAppSetting 
    2. Load File button and name it btnLoadFile 
    3. Update button and name it btnUpdate

    See the following image:

    Screen6

  3. Add the following global variables:
     Private m_strSettingName As String
     Private ConfigSettingsList As New List(Of ConfigSettings)
  4. Write the code shown below in the click event of btnLoadFile button:
         Private Sub btnLoadFile_Click(ByVal sender As System.Object, _
    		ByVal e As System.EventArgs) Handles btnLoadFile.Click
            Try
                Dim strFile As String
                Dim ConfigDoc As New XmlDocument()
                'Store the name of the file
                strFile = String.Format("{0}/_
    		ReadConfigurationAppSettingSection.exe.config", _
    		Directory.GetCurrentDirectory.ToString())
                'Load the configuration file as XML document
                ConfigDoc.Load(strFile)
                'Assign  the [applicationSettings] node 
                Dim applicationSettingsNode As XmlNode = _
    		ConfigDoc.GetElementsByTagName("applicationSettings")(0)
    
                'For reading the user settings use below
                'Dim applicationSettingsNode As XmlNode = _
    		ConfigDoc.GetElementsByTagName("userSettings")(0)
    
                ConfigSettingsList.Clear()
    
                'Run for each child node and create the ConfigSettingsList 
                'collection of [applicationSettings] child nodes
                For Each objXmlNode As XmlNode _
    		In applicationSettingsNode.FirstChild.ChildNodes
                    Dim objConfigSettings As New ConfigSettings
                    With objConfigSettings
                        .SettingName = objXmlNode.Attributes(0).Value
                        .SerializeAs = objXmlNode.Attributes(1).Value
                        .SettingValue = objXmlNode.FirstChild.InnerText
                    End With
                    ConfigSettingsList.Add(objConfigSettings)
                Next
    
                'Assign the collection to Datasource
                ConfigSettingsBindingSource.DataSource = ConfigSettingsList
            Catch ex As Exception
                MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, _
    			MessageBoxIcon.Error)
            End Try
        End Sub
    End Class
  5. Write a method which is used as predicate for finding the setting in collection:
        Private Function GetSetting(ByVal objConfigSettings As ConfigSettings) _
    	As Boolean
            Return m_strSettingName = objConfigSettings.SettingName
        End Function
  6. Write the below code in the click event of btnUpdate button:
     Private Sub btnUpdate_Click(ByVal sender As System.Object, _
    	ByVal e As System.EventArgs) Handles btnUpdate.Click
            Try
                Dim strFile As String
                Dim ConfigDoc As New XmlDocument()
                strFile = String.Format("{0}/_
    		ReadConfigurationAppSettingSection.exe.config", _
    		Directory.GetCurrentDirectory.ToString())
                ConfigDoc.Load(strFile)
                Dim applicationSettingsNode As XmlNode = _
    		ConfigDoc.GetElementsByTagName("applicationSettings")(0)
    
                'For reading the user settings use below
                'Dim applicationSettingsNode As XmlNode = _
    		ConfigDoc.GetElementsByTagName("userSettings")(0)
    
                For Each objXmlNode As XmlNode _
    		In applicationSettingsNode.FirstChild.ChildNodes
    
                    m_strSettingName = objXmlNode.Attributes(0).Value
    
                    Dim objConfigSettings As ConfigSettings = _
    			ConfigSettingsList.Find(AddressOf GetSetting)
    
                    If objConfigSettings IsNot Nothing Then
                        With objConfigSettings
                            objXmlNode.Attributes(0).Value = .SettingName
                            objXmlNode.Attributes(1).Value = .SerializeAs
                            objXmlNode.FirstChild.InnerText = .SettingValue
                        End With
                    End If
                Next
                ConfigDoc.Save(strFile)
                MessageBox.Show("Updated Successfully.", Me.Text, _
    		MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch ex As Exception
                MessageBox.Show(ex.Message, Me.Text, _
    		MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
    
        End Sub

History

  • 25th March, 2009: Initial post

License

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

Share

About the Author

sun1programmer
Team Leader IBM India Pvt. Ltd. Pune
India India
Work in Windows Forms, ASP.NET 2.0, 3.5, Portal Managements using DotNetNuke 4x., Rainbow, Windows Mobile Apllication. Having good knowledge of OOPs. Leading the team and using the cutting edge technologies for designing core components of application.
 
Having MCPD in Web Developement, MCITP Database Developer, MCTS in .NET 2.0: Web Application and SQL Server 2005.
 
Having good knowledge of Crystal Report 8.5 onwards.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberRevaOnwards28-Nov-12 20:19 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 25 Mar 2009
Article Copyright 2009 by sun1programmer
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid