溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C# Winform 更改配置文件連接數(shù)據(jù)庫不能立即生效

發(fā)布時間:2020-06-15 01:58:54 來源:網(wǎng)絡(luò) 閱讀:1702 作者:YU兒 欄目:數(shù)據(jù)庫

在程序運行過程中,配置文件只加載一次,所以動態(tài)更改后必須重新讀取一次才會生效,以下是代碼部分。

1、動態(tài)修改配置文件

          //通過Xml方式(需using System.xml;) 

           XmlDocument doc = new XmlDocument();  
            doc.Load(Application.ExecutablePath + ".config");  
            //XmlNode node = doc.SelectSingleNode(@"http://add[@key='" + key + "']"); // 定位到add節(jié)點  
            XmlNode node = doc.SelectSingleNode(@"http://add[@name='dbConnStr']"); // 定位到add節(jié)點
            XmlElement element = (XmlElement)node;
            element.SetAttribute("connectionString", "Data Source=.;Initial Catalog="";Integrated Security=True"); // 賦值 
            doc.Save(Application.ExecutablePath + ".config");
            ConfigurationManager.RefreshSection("connectionStrings"); // 刷新節(jié)點

2、每次操作數(shù)據(jù)庫的時候重新讀取配置文件節(jié)點

      string connStr =ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString;


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI