C#简单操作app.config文件

即将操作的app.config文件内容如下

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--使用自定义节点必须添加如下项, 且如下项只能在Configuration中-->
  <configSections>
    <sectionGroup name="MySettings">
      <section name="MySet" type="System.Configuration.NameValueSectionHandler"/> 
    </sectionGroup>
  </configSections>

  <connectionStrings>
<!--无密码access数据库访问方式-->
    <add name="connAcc" connectionString="Provider=Microsoft.Jet.OleDb.4.0;Data Source=db.mdb"/>
   <!--有密码access数据库访问方式-->
    <add name="conn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ./MyPasswordProtected.MDB;Jet OLEDB:Database Password=MyPassword;"/>
    <add name="ConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ./MyPasswordProtected.MDB;Jet OLEDB:Database Password=MyPassword;"/>
  </connectionStrings>

  <appSettings>
    <!--设置替换汉字-->
    <add key="splitChar" value="@"/>
    <!--设置替换汉字-->
    <add key="splitCharNew" value="囧"/>
  <!--设置每次记忆的边框-->
  <add key="biankuang" value="几字"/>
  </appSettings>
  
  <MySettings>
    <MySet>
    <add key="8公分纸竖1" value="2.7,23,-10,0.76,230"/>
    <add key="8公分纸竖2" value="2,23,30,0.81,230"/>
    <add key ="8公分纸横" value ="1.5,23,-10,0.76,220"/>
    <add key ="彩带" value="10,23,30,0.79,220"/>
    <add key ="11公分竖" value="4,23,45,0.79,340"/>
    <add key ="11公分横" value ="4,34,30,0.76,340"/>
    </MySet>
  </MySettings> 
  <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

 OperatAppConfig类内容如下, 我觉得使用微软的ConfigurationManager 在没有自定义节点时非常方便, 但是如果涉及到自定义节点后将会比较麻烦, 所以莫不如直接把app.config当做xml文件, 直接操作(需要注意的是程序在运行时其实执行的是appName.exe.config文件, 并非app.config文件):

 /// <summary>
    /// 对程序运行中的appConfig进行读写
    /// </summary>
    public class OperatAppConfig
    {
        public static bool DelXmlNode(string appNode, string key)
        {
            try
            {
                string strPath = System.Windows.Forms.Application.ExecutablePath + ".config";
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(strPath);

                XmlNode xNode = xDoc.DocumentElement.SelectSingleNode(appNode);
                 
                foreach (XmlNode item in  xNode.ChildNodes )
                {
                    // System.Console.WriteLine(item.Attributes[0].Value);
                    if (item.Attributes[0].Value == key)
                    {
                        xNode.RemoveChild(item);
                    }
                }   

                xDoc.Save(strPath);
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 对指定的节点添加子节点
        /// </summary>
        /// <param name="appNode">指定的节点名称一般为//MySettings//MySet格式</param>
        /// <param name="key">这个方法只添加add, 所以这里需要给出key和value</param>
        /// <param name="value">这个方法只添加add, 所以这里需要给出key和value</param>
        /// <returns></returns>
        public static bool AddXmlNode(string appNode,string key,string value)
        {
            try
            {
                string strPath = System.Windows.Forms.Application.ExecutablePath + ".config";
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(strPath);

                XmlNode xNode = xDoc.DocumentElement.SelectSingleNode(appNode);

                XmlElement newElement = xDoc.CreateElement("add");
               // newElement.InnerText = "black";
                newElement.SetAttribute("key", key);//添加一个带有属性的节点信息
                newElement.SetAttribute("value", value);
                xNode.AppendChild(newElement); //追加到xNode下
               //保存更改
                xDoc.Save(strPath);
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取某个指定节点下的所有key
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appValue"></param>
        public static System.Collections.Generic.List<string> GetKeys(string appNode)
        {
            System.Collections.Generic.List<string> xmlNodes = new System.Collections.Generic.List<string>();
            try
            {

                XmlDocument xDoc = new XmlDocument();
                //要注意的是使用ExecutablePath所获取的一般是 appName.exe.config文件中的内容, 而不是appName.config中的内容
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

                XmlNode xNode = xDoc.SelectSingleNode(appNode);

                foreach (XmlElement item in xNode)
                {
                    xmlNodes.Add(item.Attributes[0].Value + "囧" + item.Attributes[1].Value);
                }
                return xmlNodes;
            }
            catch
            {
                xmlNodes.Clear();
                xmlNodes.Add("默认值囧2,23,0,0.9,220");
                return xmlNodes;
            }
        }

        /// <summary>
        /// 根据键设置值
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="appValue"></param>
        public static void SetAppConfig(string appKey, string appValue)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            var xNode = xDoc.SelectSingleNode("//appSettings");

            var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
            if (xElem != null)
                xElem.SetAttribute("value", appValue);
            else
            {
                var xNewElem = xDoc.CreateElement("add");
                xNewElem.SetAttribute("key", appKey);
                xNewElem.SetAttribute("value", appValue);
                xNode.AppendChild(xNewElem);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
        }

        /// <summary>
        /// 根据键查找值
        /// </summary>
        /// <param name="appKey"></param>
        /// <returns></returns>
        public static string GetAppConfig(string appKey)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            var xNode = xDoc.SelectSingleNode("//appSettings");

            var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");

            if (xElem != null)
            {
                return xElem.Attributes["value"].Value;
            }
            return string.Empty;
        }


        /// <summary>
        /// 根据键查找值
        /// </summary>
        /// <param name="appKey"></param>
        /// <returns></returns>
        public static char GetAppConfigChar(string appKey)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

                var xNode = xDoc.SelectSingleNode("//appSettings");

                var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");

                if (xElem != null)
                {
                    return XmlConvert.ToChar(xElem.Attributes["value"].Value);
                }
            }
            catch {

                return '囧';
            }
            return '囧';
        }
    }

调用:

//获取此节点下所有的key 
OperatAppConfig.GetKeys("//MySettings//MySet");
//删除此节点下指定key的节点
 bool isDel = Common.OperatAppConfig.DelXmlNode("//MySettings//MySet", this.txtZKName.Text.Trim());
//在指定节点下新增节点
bool isAdd = Common.OperatAppConfig.AddXmlNode("//MySettings//MySet", this.txtZKName.Text.Trim(), strValue);
//根据键找值
OperatAppConfig.GetAppConfigChar("splitCharNew")

 

posted on 2017-06-22 15:06  印子  阅读(940)  评论(0编辑  收藏  举报

导航