Link to home
Start Free TrialLog in
Avatar of rocky050371
rocky050371

asked on

Overwirting a value in the app.config

VB.NET 2005

 <connectionStrings>
    <add name="Test.My.MySettings.ConnectrionString" connectionString="Data Source=(local);Initial Catalog=;User ID=;Password="
      providerName="System.Data.SqlClient" />
  </connectionStrings>
 
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
        doc.Load(fi.FullName)

        ' 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.
        doc.Save(fi.FullName)
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Runtime Web.config / App.config Editing
http://www.eggheadcafe.com/articles/20030907.asp
ASKER CERTIFIED SOLUTION
Avatar of drichards
drichards

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of drichards
drichards

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.Remove("myOtherConfig")
        cfg.AppSettings.Settings("myConfig").Value = "modifiedConfigValue"
        cfg.Save()
Avatar of rocky050371

ASKER

It was fine, worked a treat
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.