Welcome to MSDN Blogs Sign in | Join | Help

Wriju's BLOG

.NET 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!!!

Posted: Wednesday, April 02, 2008 11:02 PM by wriju

Comments

DM said:

You have to remember that it's not a good practice to do that if your application is to be installed under ProgramFiles in Windows Vista and UAC turned on.

It will also not work at all if you are logged in as a "Standard User" under WinXP or Win2000 with no rigths to modify anything under the ProgramFiles folder.

I think the technique illustrated here would be more appropriate and solid: http://msdn2.microsoft.com/en-us/vbasic/cc307956.aspx

HTH

# April 2, 2008 9:09 PM

wriju said:

Thanks DM. The URL is indeed amazing. Thanks for sharing. In Vista you can go for ClickOnce.

Wriju

# April 4, 2008 9:34 AM

Charlie Calvert's Community Blog said:

Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by the

# April 23, 2008 5:06 PM

Dave said:

I tried this and I get an error that says:

Name 'XElement' is not declared

# May 1, 2008 11:42 AM

Saranya DeviRavindran said:

I tried this:

but i got an error

XElement is not declared.

I tried adding System.Xml link on the top.

But th problem still exists.

any idea..?

# June 7, 2008 12:44 AM

wriju said:

@Saranya DeviRavindran

Add System.Xml.Linq

# June 10, 2008 8:45 AM

Ajit Kumar said:

Dear Friends,

Why you want to break your heads....

Please use this

My.Settings.Item("ConnectionString") = "Your Connection String"

# December 13, 2008 1:18 PM

wriju said:

@Ajit Kumar,

If I remember that was the issue while doing it. Then we tried the above method to achieve it.

-WG

# December 16, 2008 11:30 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker