在做Winform开发时,免不了把一些配置信息写到APP.CONFIG文件中,当程序生成后APP.CONFIG会变成以程序名+CONFIG的文件即,如程序名为A,那么生成后的APP.CONFIG文件会变成A.EXE.CONFIG文件!
直接上代码,不解释:
/// <summary> /// 配置类型 /// </summary> public enum configType { appSettings, connectionStrings } public static string GetConfig(configType cType, string keyOrName) { string result = string.Empty; if (cType == configType.appSettings) result = System.Configuration.ConfigurationManager.AppSettings[keyOrName]; else if (System.Configuration.ConfigurationManager.ConnectionStrings[keyOrName] != null) result = System.Configuration.ConfigurationManager.ConnectionStrings[keyOrName].ConnectionString; return result == null ? string.Empty : result; } /// <summary> /// 读取应用程序配置值,无相应项则返回String.Empty /// </summary> /// <param name="key">配置标识码</param> /// <returns></returns> public static string GetAppSettings(string key) { return GetConfig(configType.appSettings, key); } /// <summary> /// 修改或新建配置项 /// </summary> /// <param name="key">配置标识码</param> /// <param name="val">配置项的值</param> public static void SetAppSettings(string key, string val) { SetConfig(configType.appSettings, key, val); } public static void SetConfig(configType cType, string keyOrName, string val) //传2个参数 一个是配置文件键的名字,一个是要给这个键的值 { try { XmlDocument xDoc = new XmlDocument(); //定义XmlDocument,想操作xml一般都用这个类 string path = biovision.ihospital.his.dbCommon.db.configFilePath; //获取App.config文件绝对路径 //string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //这是获取配置文件路径的 //str = str.Substring(0, str.Length - 10) + "App.config"; //这是获取配置文件的名称 xDoc.Load(path); //读取xml XmlNode xNode; //xml节点 XmlElement xElemCurrent; //xml元素 XmlElement xElemNew; //xml元素 if (cType == configType.connectionStrings) { xNode = xDoc.SelectSingleNode("//connectionStrings"); xElemCurrent = (XmlElement)xNode.SelectSingleNode("//add[@name='" + keyOrName + "']"); if (xElemCurrent != null) xElemCurrent.SetAttribute("connectionString", val);//如果有这个键就给他赋值 else {//没有这个键就添加一个键并且赋值 xElemNew = xDoc.CreateElement("add"); xElemNew.SetAttribute("name", keyOrName); xElemNew.SetAttribute("connectionString", val); xElemNew.SetAttribute("providerName", "System.Data.SqlClient"); xNode.AppendChild(xElemNew); } } else { xNode = xDoc.SelectSingleNode("//appSettings"); xElemCurrent = (XmlElement)xNode.SelectSingleNode("//add[@key='" + keyOrName + "']"); if (xElemCurrent != null) xElemCurrent.SetAttribute("value", val);//如果有这个键就给他赋值 AppValue 就是值 else {//没有这个键就添加一个键并且赋值 xElemNew = xDoc.CreateElement("add"); xElemNew.SetAttribute("key", keyOrName); xElemNew.SetAttribute("value", val); xNode.AppendChild(xElemNew); } } xDoc.Save(path); } catch (Exception e) { Log.LogException(e, "写config配置文件出错。"); } }
后来仔细想一想,其实还有下面一种方法也可以实现config的读写功能(MS提供的,可能更好)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings[key].Value = value; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(“appSettings”);
原创代码,转载请注明出处!Enjoy ^_^