Click here to Skip to main content
15,911,360 members
Articles / Programming Languages / Visual Basic
Article

Modifying app.config File

Rate me:
Please Sign up or sign in to vote.
2.74/5 (23 votes)
22 Aug 2007CPOL1 min read 215.6K   4.7K   38   36
An article on how to change appSettings Key values of the app.config file
Screenshot - updatearticleForm.jpg

Introduction

This article will help you to change the <appSettings> values when you are deploying the application for the first time. At the time of application installation, we need to set application configuration parameters at the first time only. For example: When we change our database to another server, we can change Database Server Configuration Information into application Configuration file. At that time, we need to again modify the app.Config file by using our user Interface.

Background

The main purpose of this article is to Configure the application Configuration Settings. When we are Installing Windows Application, we have to update the app.Config file according to our requirements.

Using the Code

Here I have created a class that will help you to change the appSettings value. For that, you have to use this function with two parameters UpdateAppSettings().

You can call this function:

VB.NET
AppConfigFileSettings.UpdateAppSettings("DBServerName", txtNewKeyvalue.text)

You can update appSettings in this way:

VB.NET
// Class Name: AppConfigFileSettings
// Purpose: To Change appSettings Values

Imports System.Configuration
Imports System.Xml
''' <summary>
''' AppConfigFileSettings: This class is used to Change the 
''' AppConfigs Parameters at runtime through User Interface
''' </summary>
''' <remarks></remarks>
Public Class AppConfigFileSettings
    ''' <summary>
    ''' UpdateAppSettings: It will update the app.Config file AppConfig key values
    ''' </summary>
    ''' <param name="KeyName">AppConfigs KeyName</param>
    ''' <param name="KeyValue">AppConfigs KeyValue</param>
    ''' <remarks></remarks>
    Public Shared Sub UpdateAppSettings_
        (ByVal KeyName As String, ByVal KeyValue As String)
    '  AppDomain.CurrentDomain.SetupInformation.ConfigurationFile 
    ' This will get the app.config file path from Current application Domain
        Dim XmlDoc As New XmlDocument()
    ' Load XML Document
       XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
    ' Navigate Each XML Element of app.Config file
        For Each xElement As XmlElement In XmlDoc.DocumentElement
            If xElement.Name = "appSettings" Then
                ' Loop each node of appSettings Element 
                ' xNode.Attributes(0).Value , Mean First Attributes of Node , 
                ' KeyName Portion
                ' xNode.Attributes(1).Value , Mean Second Attributes of Node,
                ' KeyValue Portion
                 For Each xNode As XmlNode In xElement.ChildNodes
                    If xNode.Attributes(0).Value = KeyName Then
                        xNode.Attributes(1).Value = KeyValue
                    End If
                Next
            End If
        Next
        ' Save app.config file
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
    End Sub
End Class 
app.config File  
<configuration>
  <appSettings>
     <add key="DBServerName" value="Localhost"></add>
     <add key="DatabaseName" value="TestDB"></add>
     <add key="DatabaseUserID" value="sa"></add>
     <add key="DatabasePwd" value="sa"></add>
  </appSettings>
</configuration>

Points of Interest

  1. Once you run this application to change the appSettings value, it will not affect an application until you Exit the application and run it again.
  2. This article shows how to modify the app.config file. But how does this code help other users? - That depends on user requirements and your point of view.

License

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


Written By
Team Leader
India India
Jatin is Working in .Net Technology Since 2006. He has Completed Master of Science Degree in Information Technology. He Likes to learn Cutting edge technologies. He has good Skills in Asp.net, Vb.net,C#.Net, Crystal Reports,GDI+, Ajax, WCF, Silverlight SQL Server,IIS Admin,TFA ,Application Architecture Designing.

Comments and Discussions

 
GeneralRe: You almost certainly don't want to do this. Pin
Jatin Prajapati24-Mar-07 9:03
Jatin Prajapati24-Mar-07 9:03 
GeneralRe: You almost certainly don't want to do this. Pin
Shog924-Mar-07 9:11
sitebuilderShog924-Mar-07 9:11 
GeneralRe: You almost certainly don't want to do this. Pin
Jatin Prajapati24-Mar-07 9:15
Jatin Prajapati24-Mar-07 9:15 
GeneralRe: You almost certainly don't want to do this. Pin
chris196927-Mar-07 1:46
chris196927-Mar-07 1:46 
GeneralRe: You almost certainly don't want to do this. Pin
Jatin Prajapati27-Mar-07 5:28
Jatin Prajapati27-Mar-07 5:28 
GeneralRe: You almost certainly don't want to do this. Pin
Shog927-Mar-07 7:09
sitebuilderShog927-Mar-07 7:09 
GeneralRe: You almost certainly don't want to do this. [modified] Pin
chris196927-Mar-07 9:19
chris196927-Mar-07 9:19 
GeneralRe: You almost certainly don't want to do this. Pin
BruceL5-Jan-11 6:17
BruceL5-Jan-11 6:17 
Shog, I think you are REALLY missing the point and I can give you an excellent example of where this kind of code is MOST useful.

First, I am presuming that you are a bit of a Microsoft "purist" - that is, they build the tools, say "use them this way" and you follow that. I do respect that a little bit, but lets be honest about too - Microsoft has a 30 year reputation for taking the most simple things and making them OVERLY complex often for no good reason. I think this configuration stuff is an EXCELLENT example and I say this because we have been dealing with a problem with their stuff for about two months now. Every document they send us to usually begins with "this is simple" and then they go on and on with layer after layer of useless complexity. But... Let me dive into the example...

We inherited a .NET application written very early on, and to some degree very poorly where the developer writes all his config stuff, user or app, the same folder where the app is installed. In fact, he writes most of the stuff (user or app) into the app.config. Now, as you might guess, as soon as we install on Vista or Win 7 - BABOOM!!! Things go haywire. So, we studied the MS documentation for this stuff and slowly came up to speed on it with one question... (that we actually asked MS support)...

If App.Config is for the application, why would you make it un-writable when so many installs have to gather SQL connection information AT INSTALL, NOT AT SHIPMENT of product, but AT INSTALL. SQL connection strings are App level stuff, NOT user level.

Well, as you might guess MS told us that when they first released this stuff they had a "duh" moment and realized, oh yeah, this aint going to work, and as you probably know, they then added the SQL connection stuff directly, AS AN AFTERTHOUGHT.

So... In our situation we DO need to write to App.Config (for the time being) because we have a huge legacy App that we cannot start re-writing yet because we would have to "detach" all sorts of other code and re-write that, and as you likely know, you cant do that kind of work piece-meal. So, what Jatin presents DOES have a valid place, and a valid case out there.

Yes, in a more perfect world of new development, YOU are absolutely correct. But how much new development is done versus poor tortured developers like us who work for companies that MUST keep the old apps running - and must somehow work around Microsoft's as-usual stupid presumption that we are all just writing brand new glorious code each time they release something.

Jatin stated in his article that this would be good for first time install - and if you have ever worked with truly horrible code that cant be torn apart and re-written in a few days - well, he is doing the community a service.

A couple other points... All this complexity MS had thrown in there... What happens if, like us, you are producing apps that have no user based config and are always installed and controlled at the APP level? Now you have to go through all these hoops for the user stuff, when you dont need one bit of it. We asked Microsoft this, and do you know what they said? "We have to plan for the most complex..." Yeah, great response. Try flying the Space Shuttle to your local grocery store. Trust me, it will take you longer and be more expensive than a simple skateboard. Microsoft does it again!

As well, MS touts "security, security, security..." Really? Well, we encrypt just about every config setting in .NET encryption that MS is proud to point out has never been broken. So if we can do that - why do we then need to go through hoops just to do a simple config file??? Those of us around here miss the days of simple INI files - wonder why?

Jatin presents a good article that IS useful and DOES apply - especially if you ever inherit an old, crappy, poorly written, barely documented application. Give him credit for that. And then, with respect to Microsoft purists - if you want to complicate your life for no other reason that pure complexity, I suggest you try driving your car in reverse everywhere you go. Thats kind of like what Microsoft does each and every day - for what reason? Even they dont know.

Good work Jatin, good article too. Not for everyone - but for those who need it, very helpful. Cudos!
GeneralRe: You almost certainly don't want to do this. Pin
josepaulino31-May-07 13:43
josepaulino31-May-07 13:43 
GeneralRe: You almost certainly don't want to do this. Pin
prof___5618-Jul-07 17:04
prof___5618-Jul-07 17:04 

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.