读取和写入配置文件

//配置文件格式
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="lineId" value="1" />
    <add key="lineName" value="" />
    <add key="workcenterId" value="1" />
    <add key="workcenterName" value="" />
    <add key="date_begin" value="2015-12-10 00:00:00" />
    <add key="date_end" value="2015-12-10 00:00:00" />
    <add key="status" value="全部" />
  </appSettings>
</configuration>
//配置文件格式


#region 保存查询条件配置
        public void SaveConfig(string key, string value)
        {
            try
            {

                string filename = "Midea.MES.Plugin.OnlineRepair.dll.Config";
                XmlDocument doc = new XmlDocument();
                if (File.Exists(filename))
                {
                    doc.Load(filename);
                }
                else
                {
                    doc.InnerXml =
                        "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<configuration>\r\n<appSettings>\r\n</appSettings>\r\n</configuration>";
                }
                XmlNode settingNode = doc.SelectSingleNode("//configuration/appSettings");
                XmlNodeList settings = settingNode.SelectNodes("//add");

                //查询键值
                bool isfound = false;
                foreach (XmlNode x in settings)
                {
                    if (x.Attributes["key"].Value.ToUpper() == key.ToUpper())
                    {
                        isfound = true;
                        break;
                    }
                }

                //查不到键值时自动创建
                if (!isfound)
                {

                    XmlElement xe = doc.CreateElement("add");
                    xe.SetAttribute("key", key);
                    xe.SetAttribute("value", value);
                    settingNode.AppendChild(xe);
                    doc.Save(filename);

                }
                Configuration config = ConfigurationManager.OpenExeConfiguration("Midea.MES.Plugin.OnlineRepair.dll");
                config.AppSettings.Settings.Remove(key);
                config.AppSettings.Settings.Add(key, value);
                config.Save();
            }
            catch
            {

            }

        }
        #endregion

        #region 获取参数
        public string GetConfig(string key)
        {
            try
            {



                string filename = "Midea.MES.Plugin.OnlineRepair.dll.Config";
                if (File.Exists(filename) == false)
                {
                    return "";
                }
                string value = "";
                Configuration config = ConfigurationManager.OpenExeConfiguration("Midea.MES.Plugin.OnlineRepair.dll");
                value = config.AppSettings.Settings[key].Value;
                return value;
            }
            catch (Exception ex)
            {
                return "";
            }

        }
        #endregion

    }


你可能感兴趣的:(配置文件,public)