C#读写config配置文件的方法
如下所示:
<?xmlversion="1.0"encoding="utf-8"?> <configuration> <appSettings> <addkey="ServerIP"value="127.0.0.1"></add> <addkey="DataBase"value="WarehouseDB"></add> <addkey="user"value="sa"></add> <addkey="password"value="sa"></add> </appSettings> </configuration>
对config配置文件的读写类
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Text.RegularExpressions; usingSystem.Configuration; usingSystem.ServiceModel; usingSystem.ServiceModel.Configuration; namespaceNetUtilityLib { publicstaticclassConfigHelper { //依据连接串名字connectionName返回数据连接字符串 publicstaticstringGetConnectionStringsConfig(stringconnectionName) { //指定config文件读取 stringfile=System.Windows.Forms.Application.ExecutablePath; System.Configuration.Configurationconfig=ConfigurationManager.OpenExeConfiguration(file); stringconnectionString= config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString(); returnconnectionString; } ///<summary> ///更新连接字符串 ///</summary> ///<paramname="newName">连接字符串名称</param> ///<paramname="newConString">连接字符串内容</param> ///<paramname="newProviderName">数据提供程序名称</param> publicstaticvoidUpdateConnectionStringsConfig(stringnewName,stringnewConString,stringnewProviderName) { //指定config文件读取 stringfile=System.Windows.Forms.Application.ExecutablePath; Configurationconfig=ConfigurationManager.OpenExeConfiguration(file); boolexist=false;//记录该连接串是否已经存在 //如果要更改的连接串已经存在 if(config.ConnectionStrings.ConnectionStrings[newName]!=null) { exist=true; } //如果连接串已存在,首先删除它 if(exist) { config.ConnectionStrings.ConnectionStrings.Remove(newName); } //新建一个连接字符串实例 ConnectionStringSettingsmySettings= newConnectionStringSettings(newName,newConString,newProviderName); //将新的连接串添加到配置文件中. config.ConnectionStrings.ConnectionStrings.Add(mySettings); //保存对配置文件所作的更改 config.Save(ConfigurationSaveMode.Modified); //强制重新载入配置文件的ConnectionStrings配置节 ConfigurationManager.RefreshSection("ConnectionStrings"); } ///<summary> ///返回*.exe.config文件中appSettings配置节的value项 ///</summary> ///<paramname="strKey"></param> ///<returns></returns> publicstaticstringGetAppConfig(stringstrKey) { stringfile=System.Windows.Forms.Application.ExecutablePath; Configurationconfig=ConfigurationManager.OpenExeConfiguration(file); foreach(stringkeyinconfig.AppSettings.Settings.AllKeys) { if(key==strKey) { returnconfig.AppSettings.Settings[strKey].Value.ToString(); } } returnnull; } ///<summary> ///在*.exe.config文件中appSettings配置节增加一对键值对 ///</summary> ///<paramname="newKey"></param> ///<paramname="newValue"></param> publicstaticvoidUpdateAppConfig(stringnewKey,stringnewValue) { stringfile=System.Windows.Forms.Application.ExecutablePath; Configurationconfig=ConfigurationManager.OpenExeConfiguration(file); boolexist=false; foreach(stringkeyinconfig.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下所有服务终结点的IP地址 publicstaticvoidUpdateServiceModelConfig(stringconfigPath,stringserverIP) { Configurationconfig=ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroupsec=config.SectionGroups["system.serviceModel"]; ServiceModelSectionGroupserviceModelSectionGroup=secasServiceModelSectionGroup; ClientSectionclientSection=serviceModelSectionGroup.Client; foreach(ChannelEndpointElementiteminclientSection.Endpoints) { stringpattern=@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; stringaddress=item.Address.ToString(); stringreplacement=string.Format("{0}",serverIP); address=Regex.Replace(address,pattern,replacement); item.Address=newUri(address); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("system.serviceModel"); } //修改applicationSettings中App.Properties.Settings中服务的IP地址 publicstaticvoidUpdateConfig(stringconfigPath,stringserverIP) { Configurationconfig=ConfigurationManager.OpenExeConfiguration(configPath); ConfigurationSectionGroupsec=config.SectionGroups["applicationSettings"]; ConfigurationSectionconfigSection=sec.Sections["DataService.Properties.Settings"]; ClientSettingsSectionclientSettingsSection=configSectionasClientSettingsSection; if(clientSettingsSection!=null) { SettingElementelement1=clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS"); if(element1!=null) { clientSettingsSection.Settings.Remove(element1); stringoldValue=element1.Value.ValueXml.InnerXml; element1.Value.ValueXml.InnerXml=GetNewIP(oldValue,serverIP); clientSettingsSection.Settings.Add(element1); } SettingElementelement2=clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS"); if(element2!=null) { clientSettingsSection.Settings.Remove(element2); stringoldValue=element2.Value.ValueXml.InnerXml; element2.Value.ValueXml.InnerXml=GetNewIP(oldValue,serverIP); clientSettingsSection.Settings.Add(element2); } } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("applicationSettings"); } privatestaticstringGetNewIP(stringoldValue,stringserverIP) { stringpattern=@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"; stringreplacement=string.Format("{0}",serverIP); stringnewvalue=Regex.Replace(oldValue,pattern,replacement); returnnewvalue; } } }
测试代码如下:
classProgram { staticvoidMain(string[]args) { try { //stringfile=System.Windows.Forms.Application.ExecutablePath+".config"; //stringfile1=AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; stringserverIP=ConfigHelper.GetAppConfig("ServerIP"); stringdb=ConfigHelper.GetAppConfig("DataBase"); stringuser=ConfigHelper.GetAppConfig("user"); stringpassword=ConfigHelper.GetAppConfig("password"); Console.WriteLine(serverIP); Console.WriteLine(db); Console.WriteLine(user); Console.WriteLine(password); ConfigHelper.UpdateAppConfig("ServerIP","192.168.1.11"); stringnewIP=ConfigHelper.GetAppConfig("ServerIP"); Console.WriteLine(newIP); Console.ReadKey(); } catch(Exceptionex) { Console.WriteLine(ex.Message); } } }
以上这篇C#读写config配置文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。