转自:http://www.cnblogs.com/xiaoziyo/p/4364073.html

很多时候我们需要对系统的.config文件进度读写操作,例如:系统初始化的参数的更改、系统参数的改变都需要更新到配置文件。

    首先我们有必要了解一下app.config、exe.config和vshost.exe.config作用和区别:

    vshost.exe.config是程序运行时的配置文本,exe.config是程序运行后会复制到vshost.exe.config,app.config是在vshost.exe.config和exe.config没有情况起作用,从app.config复制到exe.config再复制到vshost.exe.config。vshost.exe.config和exe.config会自动创建内容跟app.config一样。了解过这些其实写配置文件都是写到exe.config文件中了,app.config不会变化。网上也有许多关于配置文件的读写操作,也是借鉴了多位前辈的经验自己总结的一些比较常用的读写操作。废话不多说,直接上主题:

  1. appSetting节点

    复制代码

     1           /// <summary> 2          /// 修改AppSettings中配置 3          /// </summary> 4          /// <param name="key">key值</param> 5          /// <param name="value">相应值</param> 6          public static bool SetConfigValue(string key, string value) 7          { 8              try 9              {10                  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);11                  if (config.AppSettings.Settings[key] != null)12                      config.AppSettings.Settings[key].Value = value;13                  else14                      config.AppSettings.Settings.Add(key, value);15                  config.Save(ConfigurationSaveMode.Modified);16                  ConfigurationManager.RefreshSection("appSettings");17                  return true;18              }19              catch20              {21                  return false;22              }23          }

    复制代码

     

    复制代码

     1         /// <summary> 2         /// 获取AppSettings中某一节点值 3         /// </summary> 4         /// <param name="key"></param> 5         public static string GetConfigValue(string key) 6         { 7                 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 8                 if (config.AppSettings.Settings[key] != null) 9                      return  config.AppSettings.Settings[key].Value;10                 else11                   12                 return string.Empty;13         }

    复制代码

     

  2. ConnectionStrings节点

    复制代码

     1         /// <summary> 2         /// 获取连接节点值 3         /// </summary> 4         /// <param name="key"></param> 5         /// <returns></returns> 6         public static string GetConnectionValue(string key) 7         { 8             if (ConfigurationManager.ConnectionStrings[key] != null) 9                 return ConfigurationManager.ConnectionStrings[key].ConnectionString;10             return string.Empty;11         }

    复制代码

     

    复制代码

     1  public static void UpdateConnectionStringsConfig(string key, string conString) 2         { 3             bool isModified = false;    //记录该连接串是否已经存在  4             if (ConfigurationManager.ConnectionStrings[key] != null) 5             { 6                 isModified = true; 7             } 8             //新建一个连接字符串实例  9             ConnectionStringSettings mySettings = new ConnectionStringSettings(key, conString);10 11             // 打开可执行的配置文件*.exe.config 12             Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);13 14             // 如果连接串已存在,首先删除它 15             if (isModified)16             {17                 config.ConnectionStrings.ConnectionStrings.Remove(key);18             }19             // 将新的连接串添加到配置文件中. 20             config.ConnectionStrings.ConnectionStrings.Add(mySettings);21             // 保存对配置文件所作的更改 22             config.Save(ConfigurationSaveMode.Modified);23             // 强制重新载入配置文件的ConnectionStrings配置节  24             ConfigurationManager.RefreshSection("connectionStrings");25         }

    复制代码

     

  3. System.ServiceModel节点

    复制代码

     1         /// <summary> 2         /// 读取EndpointAddress 3         /// </summary> 4         /// <param name="endpointName"></param> 5         /// <returns></returns> 6         public static string GetEndpointClientAddress(string endpointName) 7         { 8             ClientSection clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection; 9             foreach (ChannelEndpointElement item in clientSection.Endpoints)10             {11                 if (item.Name == endpointName)12                     return item.Address.ToString();13             }14             return string.Empty;15         }16 17 18         /// <summary>19         /// 设置EndpointAddress20         /// </summary>21         /// <param name="endpointName"></param>22         /// <param name="address"></param>23         public static bool SetEndpointClientAddress(string endpointName, string address)24         {25             try26             {27                 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);28                 ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;29                 foreach (ChannelEndpointElement item in clientSection.Endpoints)30                 {31                     if (item.Name != endpointName)32                         continue;33                     item.Address = new Uri(address);34                     break;35                 }36                 config.Save(ConfigurationSaveMode.Modified);37                 ConfigurationManager.RefreshSection("system.serviceModel");38                 return true;39             }40             catch (Exception ex)41             {42                 return false;43             }44 45         }

    复制代码

     

     

     

     对与配置文件的修改有些可能会觉得直接操作config文件对安全性来说代价太高了,这种情况下就需要个人取决一下可以使用将appconfig段放到独立的config文件中,以XML的方式进行修改,并可以避免应用程序重启的问题。

     简单的再说一下放到独立文件的操作

      

     剩下的就是对xml的操作

      

      

复制代码

 1              string ConnectConfigPath = AppData.StartupPath + "\\Config\\DaoConfig.xml";//获取配置文件路径 2  3                 //向DaoConfig里添加节点 4                 XmlDocument xmlDoc = new XmlDocument(); 5                 xmlDoc.Load(ConnectConfigPath); 6                 XmlNode xmldocSelect = xmlDoc.SelectSingleNode("/DaoConfig[1]"); 7  8                 xmldocSelect.RemoveAll();//删除当前节点的所有子节点 9 10                 //添加test节点11                 XmlElement Account = xmlDoc.CreateElement("test");12                 Account.InnerText = "对应的值";13                 xmldocSelect.AppendChild(Account);14 15 16                 xmlDoc.Save(ConnectConfigPath);