C#讀寫config配置文件的方法
如下所示:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ServerIP" value="127.0.0.1"></add> <add key="DataBase" value="WarehouseDB"></add> <add key="user" value="sa"></add> <add key="password" value="sa"></add> </appSettings> </configuration>
對config配置文件的讀寫類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Configuration; using System.ServiceModel; using System.ServiceModel.Configuration; namespace NetUtilityLib { public static class ConfigHelper { //依據(jù)連接串名字connectionName返回數(shù)據(jù)連接字符串 public static string GetConnectionStringsConfig(string connectionName) { //指定config文件讀取 string file = System.Windows.Forms.Application.ExecutablePath; System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file); string connectionString = config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString(); return connectionString; } ///<summary> ///更新連接字符串 ///</summary> ///<param name="newName">連接字符串名稱</param> ///<param name="newConString">連接字符串內(nèi)容</param> ///<param name="newProviderName">數(shù)據(jù)提供程序名稱</param> public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName) { //指定config文件讀取 string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; //記錄該連接串是否已經(jīng)存在 //如果要更改的連接串已經(jīng)存在 if (config.ConnectionStrings.ConnectionStrings[newName] != null) { exist = true; } // 如果連接串已存在,首先刪除它 if (exist) { config.ConnectionStrings.ConnectionStrings.Remove(newName); } //新建一個連接字符串實例 ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName); // 將新的連接串添加到配置文件中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); // 保存對配置文件所作的更改 config.Save(ConfigurationSaveMode.Modified); // 強制重新載入配置文件的ConnectionStrings配置節(jié) ConfigurationManager.RefreshSection("ConnectionStrings"); } ///<summary> ///返回*.exe.config文件中appSettings配置節(jié)的value項 ///</summary> ///<param name="strKey"></param> ///<returns></returns> public static string GetAppConfig(string strKey) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == strKey) { return config.AppSettings.Settings[strKey].Value.ToString(); } } return null; } ///<summary> ///在*.exe.config文件中appSettings配置節(jié)增加一對鍵值對 ///</summary> ///<param name="newKey"></param> ///<param name="newValue"></param> public static void UpdateAppConfig(string newKey, string newValue) { string file = System.Windows.Forms.Application.ExecutablePath; Configuration config = ConfigurationManager.OpenExeConfiguration(file); bool exist = false; foreach (string key in config.AppSettings.Settings.AllKeys) { if (key == newKey) { exist = true; } } if (exist) { config.AppSettings.Settings.Remove(newKey); } config.AppSettings.Settings.Add(newKey, newValue); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } // 修改system.serviceModel下所有服務(wù)終結(jié)點的IP地址 public static void UpdateServiceModelConfig(string configPath, string serverIP) { Configuration config = ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"]; ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup; ClientSection clientSection = serviceModelSectionGroup.Client; foreach (ChannelEndpointElement item in clientSection.Endpoints) { string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; string address = item.Address.ToString(); string replacement = string.Format("{0}", serverIP); address = Regex.Replace(address, pattern, replacement); item.Address = new Uri(address); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("system.serviceModel"); } // 修改applicationSettings中App.Properties.Settings中服務(wù)的IP地址 public static void UpdateConfig(string configPath, string serverIP) { Configuration config = ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"]; ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"]; ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection; if (clientSettingsSection != null) { SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS"); if (element1 != null) { clientSettingsSection.Settings.Remove(element1); string oldValue = element1.Value.ValueXml.InnerXml; element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP); clientSettingsSection.Settings.Add(element1); } SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS"); if (element2 != null) { clientSettingsSection.Settings.Remove(element2); string oldValue = element2.Value.ValueXml.InnerXml; element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP); clientSettingsSection.Settings.Add(element2); } } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("applicationSettings"); } private static string GetNewIP(string oldValue, string serverIP) { string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; string replacement = string.Format("{0}", serverIP); string newvalue = Regex.Replace(oldValue, pattern, replacement); return newvalue; } } }
測試代碼如下:
class Program { static void Main(string[] args) { try { //string file = System.Windows.Forms.Application.ExecutablePath + ".config"; //string file1 = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; string serverIP = ConfigHelper.GetAppConfig("ServerIP"); string db = ConfigHelper.GetAppConfig("DataBase"); string user = ConfigHelper.GetAppConfig("user"); string password = ConfigHelper.GetAppConfig("password"); Console.WriteLine(serverIP); Console.WriteLine(db); Console.WriteLine(user); Console.WriteLine(password); ConfigHelper.UpdateAppConfig("ServerIP", "192.168.1.11"); string newIP = ConfigHelper.GetAppConfig("ServerIP"); Console.WriteLine(newIP); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
以上這篇C#讀寫config配置文件的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持我們。
上一篇:詳解C# Socket簡單例子(服務(wù)器與客戶端通信)
欄 目:C#教程
下一篇:詳解C#中委托,事件與回調(diào)函數(shù)講解
本文標(biāo)題:C#讀寫config配置文件的方法
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6144.html
您可能感興趣的文章
- 01-10C#讀寫INI文件的方法
- 01-10c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法
- 01-10VS中C#讀取app.config數(shù)據(jù)庫配置字符串的三種方法
- 01-10輕松學(xué)習(xí)C#的讀寫操作
- 01-10使用C#實現(xiàn)讀取系統(tǒng)配置文件的代碼實例講解
- 01-10舉例說明Java多線程編程中讀寫鎖的使用
- 01-10C#讀寫指定編碼格式的文本文件
- 01-10Windows系統(tǒng)中C#讀寫ini配置文件的程序代碼示例分享
- 01-10C# FileStream文件讀寫詳解
- 01-10C#編程實現(xiàn)動態(tài)改變配置文件信息的方法


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻 器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-10C#中split用法實例總結(jié)
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法