using System.IO;
using System.Xml;

namespace LJLib.Tools.File
{
    public static class AppConfig
    {
        /// <summary>
        /// 设置xml值
        /// </summary>
        /// <param name="xmlPath">xml文件名</param>
        /// <param name="keyname">值名</param>
        /// <param name="value">取值</param>
        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("<configuration/>");
            }
            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);
        }

        /// <summary>
        /// 读取xml值
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="keyname"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        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("<configuration/>");
            }
            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");
            }
        }
    }
}
