Wriju's BLOG

.NET, Cloud and everything

LINQ to XML : Changing connectionString in app.config

When you create data bind application using wizard in Windows Forms application and connection string gets added to you settings file. Now you may be interested in changing that connection string but problems,


1)     The connection string in settings has an Application Scope so it is ReadOnly property. You modify and remove “ReadOnly” from .vb file but it gets refreshed whenever you try to add new or modify anything.


2)     Things in Settings gets stored into <applicationName>.exe.config file.


 


I took the challenge to alter the app.config file and save it again. During my try I found that LINQ to XML is the easiest way to alter with its powerful API. So the sample I have created does looks for the first <connectionString> in the <connectionStrings> section and then alters the connectionString attribute of <add element.


 


Actually in app.config the section looks like,


<connectionStrings>


    <add name=AppConfigChange.My.MySettings.Connstr


        connectionString=


Data Source=wghosh2k3\sqlexpress;Initial Catalog=Northwind;Integrated Security=True


        providerName=System.Data.SqlClient />


 


I am changing the highlighted part and saving it back to the same file.


 


And the code looks like,


 


Dim sNewConnStr As String = “”


 


‘Get the file info


Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)


 


‘Load the file info


Dim xml = XElement.Load(config.FilePath)


 


‘Get the first config section (first connection string info)


Dim connStrXML = xml.Descendants(“connectionStrings”).Elements().First()


 


‘Get the connection string value


Dim connStr = connStrXML.Attribute(“connectionString”).Value


 


‘Create an array with ‘;’


Dim arrConn() As String = connStr.Split(“;”)


 


For i As Int16 = 0 To arrConn.Length – 1


    ‘Get the attribute and value splitted by “=”


    Dim arrSubConn() As String = arrConn(i).Split(“=”)


    If (arrSubConn.Length = 2) Then


        Dim sConnAttr As String = “”


        Dim sConnValue As String = “”


        sConnAttr = arrSubConn(0)


        sConnValue = arrSubConn(1)


 


        ‘Change Database name


        If (sConnAttr = “Initial Catalog”) Then


            ‘This is the place where you will be changing the database name


            sConnValue = “NewDBName”       


   End If


 


        ‘Generate newly altered connection string


        sNewConnStr += sConnAttr + “=” + sConnValue + “;”


    End If


Next


 


After doing everything you need to save it back to the same file,


 


‘Modify the existing connection string information


connStrXML.SetAttributeValue(“connectionString”, sNewConnStr)


 


‘Saving config at the same place


xml.Save(config.FilePath)


 


 


Namoskar!!!