Overwirting a value in the app.config

Posted on 2007-07-26
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
    LVL 53

    Expert Comment

    Runtime Web.config / App.config Editing
    LVL 19

    Accepted Solution

    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

    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

    It was fine, worked a treat
    LVL 19

    Expert Comment

    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

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

    755 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

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now