using System.IO; using System.Xml; namespace LJLib.Tools.File { public static class AppConfig { /// /// 设置xml值 /// /// xml文件名 /// 值名 /// 取值 public static void SetXmlFileValue(string xmlPath, string keyname, string value) { FileStream file = System.IO.File.Open(xmlPath, FileMode.OpenOrCreate); XmlDocument xDoc = new XmlDocument(); try { xDoc.Load(file); } catch (System.Exception) { xDoc.LoadXml(""); } file.Close(); XmlNode xRoot = xDoc.DocumentElement; XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("appSettings"); if (xSection == null) { xSection = xDoc.CreateElement("appSettings"); xRoot.AppendChild(xSection); } XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']"); if (xElem != null) { xElem.SetAttribute("value", value); } else { XmlElement xTmpElem = xDoc.CreateElement("add"); xTmpElem.SetAttribute("key", keyname); xTmpElem.SetAttribute("value", value); xSection.AppendChild(xTmpElem); } xDoc.Save(xmlPath); } /// /// 读取xml值 /// /// /// /// /// public static string GetXmlFileValue(string xmlPath, string keyname, string defaultValue) { if (!System.IO.File.Exists(xmlPath)) { return defaultValue; } FileStream file = System.IO.File.OpenRead(xmlPath); XmlDocument xDoc = new XmlDocument(); try { xDoc.Load(file); } catch (System.Exception) { xDoc.LoadXml(""); } file.Close(); XmlNode xRoot = xDoc.DocumentElement; XmlElement xSection = (XmlElement)xRoot.SelectSingleNode("appSettings"); if (xSection == null) { return defaultValue; } XmlElement xElem = (XmlElement)xSection.SelectSingleNode("add[@key='" + keyname + "']"); if (xElem == null) { return defaultValue; } else { return xElem.GetAttribute("value"); } } } }