详解C#如何读写config配置文件

详解C#如何读写config配置文件,第1张

概述配置文件概述:应用程序配置文件是标准的XML文件,XML标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是configuration。我们经常访

配置文件概述:

应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是configuration。我们经常访问的是appSettings,它是由.Net预定义的配置节。我们经常使用的配置文件的架构是客诉下面的形式。先大概有个印象,通过后面的实例会有一个比较清楚的认识。下面的“配置节”可以理解为进行配置一个XML的节点。

对于一个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 {  //依据连接串名字connectionname返回数据连接字符串   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">连接字符串内容</param>   ///<param name="newProvIDername">数据提供程序名称</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; //记录该连接串是否已经存在    //如果要更改的连接串已经存在    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配置节    ConfigurationManager.RefreshSection("ConnectionStrings");  }  ///<summary>   ///返回*.exe.config文件中appSettings配置节的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配置节增加一对键值对   ///</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下所有服务终结点的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}\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中服务的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}\b";   string replacement = string.Format("{0}",serverIP);   string newvalue = Regex.Replace(oldValue,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配置文件全部内容,希望文章能够帮你解决详解C#如何读写config配置文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1253660.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存