using System; using System.Windows.Forms; using System.Xml; namespace BlackBoxForms.App_Code { /// <summary> /// 设置配置文件 /// </summary> public class SetAppConfig { public static string AppConfig() { return System.IO.Path.Combine(Application.StartupPath, "BlackBoxForms.exe.config"); } /// <summary> /// 根据WCF获取值 /// </summary> /// <param name="appKey">key</param> /// <returns>value</returns> public static string GetAddress(string appKey) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppConfig()); XmlNode xNode = xmlDoc.SelectSingleNode("//system.serviceModel//client"); XmlElement xElem = (XmlElement)xNode.SelectSingleNode("//endpoint[@name='" + appKey + "']"); if (xElem != null) return xElem.GetAttribute("address"); else return ""; } catch (Exception) { return ""; } } /// <summary> /// 设置WCF服务 /// </summary> /// <param name="appKey">key</param> /// <param name="appValue">value</param> /// <returns>结果 true:成功,false:失败</returns> public static bool SetValueByName(string appKey, string appValue) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppConfig()); XmlNode xNode = xmlDoc.SelectSingleNode("//system.serviceModel//client"); XmlElement xElem1 = (XmlElement)xNode.SelectSingleNode("//endpoint[@name='" + appKey + "']"); if (xElem1 != null) { xElem1.SetAttribute("address", appValue); } else { XmlElement xElem2 = xmlDoc.CreateElement("endpoint"); xElem2.SetAttribute("name", appKey); xElem2.SetAttribute("address", appValue); xNode.AppendChild(xElem2); } xmlDoc.Save(AppConfig()); return true; } catch (Exception) { return false; } } /// <summary> /// 根据key获取value值 /// </summary> /// <param name="appKey">key</param> /// <returns>value</returns> public static string GetValue(string appKey) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppConfig()); XmlNode xNode = xmlDoc.SelectSingleNode("//appSettings"); XmlElement xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']"); if (xElem != null) return xElem.GetAttribute("value"); else return ""; } catch (Exception) { return ""; } } /// <summary> /// 根据key设置value值 /// </summary> /// <param name="appKey">key</param> /// <param name="appValue">value</param> /// <returns>结果 true:成功,false:失败</returns> public static bool SetValueByKey(string appKey, string appValue) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppConfig()); XmlNode xNode = xmlDoc.SelectSingleNode("//appSettings"); XmlElement xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']"); if (xElem1 != null) { xElem1.SetAttribute("value", appValue); } else { XmlElement xElem2 = xmlDoc.CreateElement("add"); xElem2.SetAttribute("key", appKey); xElem2.SetAttribute("value", appValue); xNode.AppendChild(xElem2); } xmlDoc.Save(AppConfig()); return true; } catch (Exception) { return false; } } } }