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!!!
Comments
Anonymous
April 02, 2008
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 HTHAnonymous
April 04, 2008
Thanks DM. The URL is indeed amazing. Thanks for sharing. In Vista you can go for ClickOnce. WrijuAnonymous
April 23, 2008
Welcome to the forty-third issue of Community Convergence. The last few weeks have been consumed by theAnonymous
May 01, 2008
I tried this and I get an error that says: Name 'XElement' is not declaredAnonymous
June 06, 2008
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..?Anonymous
June 10, 2008
@Saranya DeviRavindran Add System.Xml.LinqAnonymous
August 28, 2008
Imports System.Xml.Linq Dim xml As String = XElement.Load(config.FilePath) Error 2 Name 'XElement' is not declared I have tried this but still gets this Error. I can Imports System.Xml but the Linq is not an option I can choose. Do I miss any reference?Anonymous
August 29, 2008
When i Write Imports System.Xml.Linq I get the message: Namespace or type specified in the Imports 'System.Xml.Linq' dosn't contain any public member or cannot be found. Linq is not an option I can choose in the drop down menu. Dim xml As String = XElement.Load(config.FilePath) gives the Error: Name 'XElement' is not declared. Dim connStrXML As String = xml.Descendants("connectionStrings").Elements().First() gives the Error: 'Descendants' is not a member of 'String'.Anonymous
December 13, 2008
Dear Friends, Why you want to break your heads.... Please use this My.Settings.Item("ConnectionString") = "Your Connection String"Anonymous
December 16, 2008
@Ajit Kumar, If I remember that was the issue while doing it. Then we tried the above method to achieve it. -WGAnonymous
September 06, 2009
I am having more than one connection strings under the section <connectionStrings> in my app.config. I want to make changes (replace) a particular word ('local') with my own word (i.e. 'AssetId'). I tried using the below code and also thru looping but it did not help.
var connStrXML1 = xml.Descendants("connectionStrings").ElementAt(1); var connStr1 = connStrXML1.Attribute("connectionString").Value; sNewConnStr1 = connStr1.Replace("(local)", sNewDBName); connStrXML1.SetAttributeValue("connectionString", sNewConnStr1);
Please HELP! and do let me know if u have any inputs. Regards, Swati
- Anonymous
February 06, 2010
When i use this code, it erases whole "connectionString" value. I don't figure out why? please help... (I use VS 2008 Pro) Judasis