心 涯

NET&JAVA&PHP(要跨界,你不只要跨「脑」的界限,更要跨越「心」的界限,不怕改变,不怕再学习!)

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
    

<connectionStrings>

    <addname="AppConfigChange.My.MySettings.Connstr"

        connectionString=

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

        providerName="System.Data.SqlClient" />

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)

posted on 2008-04-05 23:21  witer666  阅读(744)  评论(2编辑  收藏  举报