using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;namespace ConsoleApplication1{ ////// 配置文件工具类 /// public static class ConfigUtil { ////// 修改Config配置文件的值 /// /// /// /// public static void SetAppSettingsExe(string filePath, string key, string newValue) { try { var doc = new XmlDocument(); doc.Load(filePath); doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value = newValue; doc.Save(filePath); doc.Load(filePath); doc = null; } catch (Exception ex) { throw ex; } } ////// 获取Config配置文件的值 /// /// /// public static string GetAppSettingsExe(string filePath, string key) { try { var doc = new XmlDocument(); doc.Load(filePath); return doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value; } catch (Exception ex) { throw ex; } } ////// 修改vshost.exe.Config配置文件的值 /// /// /// public static void SetAppSettingsVshostExe(string key, string value) { try { //vshost.exe.Config var doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value = value; doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); } catch (Exception ex) { throw ex; } } ////// 获取vshost.exe.Config配置文件的值 /// /// ///public static string GetAppSettingsVshostExe(string key) { try { var doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); return doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value; } catch (Exception ex) { throw ex; } } }}
调用:
ConfigUtil.SetAppSettingsVshostExe("aa123", "你们"); var v = ConfigUtil.GetAppSettingsExe(@"E:\项目\ConsoleApplication1\app.config", "aa"); var v2 = ConfigUtil.GetAppSettingsVshostExe("aa"); ConfigUtil.SetAppSettingsExe(@"E:\项目\ConsoleApplication1\app.config", "aa", "马");