动态操作.Config文件

本文介绍了一个用于动态修改和读取App.config文件中appSettings部分的方法。通过提供的公共静态方法,可以方便地设置和获取配置项的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 /**//// <summary>
 2        /// Dynamic Write App.config
 3        /// </summary>
 4        /// <param name="AppKey"></param>
 5        /// <param name="AppValue"></param>

 6        public static void SetValue(string AppKey, string AppValue)
 7        {
 8            XmlDocument xDoc = new XmlDocument();
 9            //获取可执行文件的路径和名称
10            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
11
12            XmlNode xNode;
13            XmlElement xElem1;
14            XmlElement xElem2;
15            xNode = xDoc.SelectSingleNode("//appSettings");
16
17            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
18            if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
19            else
20            {
21                xElem2 = xDoc.CreateElement("add");
22                xElem2.SetAttribute("key", AppKey);
23                xElem2.SetAttribute("value", AppValue);
24                xNode.AppendChild(xElem2);
25            }

26            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
27        }

28
29        /**//// <summary>
30        /// Reader App.config
31        /// </summary>
32        /// <param name="appKey"></param>
33        /// <returns></returns>

34        public static string GetConfigValue(string appKey)
35        {
36            XmlDocument xDoc = new XmlDocument();
37            try
38            {
39                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
40
41                XmlNode xNode;
42                XmlElement xElem;
43                xNode = xDoc.SelectSingleNode("//appSettings");
44                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
45                if (xElem != null)
46                    return xElem.GetAttribute("value");
47                else
48                    return String.Empty;
49            }

50            catch (Exception)
51            {
52                return "";
53            }

54        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值