Overwirting a value in the app.config

Posted on 2007-07-26
Medium Priority
Last Modified: 2011-10-03
VB.NET 2005

    <add name="Test.My.MySettings.ConnectrionString" connectionString="Data Source=(local);Initial Catalog=;User ID=;Password="
      providerName="System.Data.SqlClient" />
I want to overwrite a connectionstring in the app.config fiel        

        Dim asm As Assembly = Assembly.GetExecutingAssembly
        Dim fi As FileInfo = New FileInfo(asm.Location + ".config")

        Dim sConnectionString As String = "Data Source=*;Initial Catalog=;User ID=;Password="
        Dim sNewConnectionString As String = sConnectionString.Replace("*", serverName)

        ' Loads the config file into the XML DOM.
        Dim doc As New System.Xml.XmlDataDocument

        ' Finds the right node and change it to the new value.
        Dim node As XmlNode
        For Each node In doc.Item("configuration").Item("connectionStrings")
            If node.Name = "add" Then
>>> UNSURE WHAT TO DO HERE              

I used to use

       If Node.Name = "add" Then
                If Node.Attributes.GetNamedItem("key").Value = "cn" Then
                    Node.Attributes.GetNamedItem("value").Value = newCn

but these are no longer supported and the app.config file has changed

             End If
        Next node

        ' Write out the new config file.
Question by:rocky050371
  • 3
LVL 53

Expert Comment

ID: 19573698
Runtime Web.config / App.config Editing
LVL 19

Accepted Solution

drichards earned 2000 total points
ID: 19574929
There is an API for managing config files.  See the docs for ConfigurationManager:

You can use the default app config (like in my sample code) of you can specify a specific file.  You can even encrypt sections (like the connectionStrings section if you put passwords in the config file).

Here is some code that modifies config values:

            Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            cfg.ConnectionStrings.ConnectionStrings["Test.My.MySettings.ConnectrionString"].ConnectionString = "Data Source=localhost;Initial Catalog=;User ID=me;Password=password";
            cfg.AppSettings.Settings.Add("newKey", "newValue");
            cfg.AppSettings.Settings["myConfig"].Value = "modifiedConfigValue";

based on this config:

<?xml version="1.0" encoding="utf-8" ?>
    <add key="myConfig" value="myConfigValue"/>
    <add key="myOtherConfig" value="myOtherValue"/>
    <add name="Test.My.MySettings.ConnectrionString" connectionString="Data Source=(local);Initial Catalog=;User ID=;Password="
      providerName="System.Data.SqlClient" />
LVL 19

Expert Comment

ID: 19575733
I suppose I should have put up VB code for this one...

        Dim cfg As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        cfg.ConnectionStrings.ConnectionStrings("Test.My.MySettings.ConnectrionString").ConnectionString = "Data Source=localhost;Initial Catalog=;User ID=me;Password=password"
        cfg.AppSettings.Settings.Add("newKey", "newValue")
        cfg.AppSettings.Settings("myConfig").Value = "modifiedConfigValue"

Author Comment

ID: 19575776
It was fine, worked a treat
LVL 19

Expert Comment

ID: 19575787
Also, if you run this in Visual Studio, don't be surprised if the <project>.exe.config is not changed when you are finished.  In C# the environment leaves it changed on disk, but VB seems to replace it with the app.config source when the program is complete.  If you want to see the resulting config file, you have to run the exe outside of the Visual Studio environment.  And if you run it in the debugger, it uses the <project>.vshost.exe.config and not the <project>.exe.config.

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question