c#.net写入app.config

今天写了个 windows的小程序,把我郁闷了够戗.太久没有接触了。就把一点儿小玩意儿写下来,以方便大家以后查阅.
读取app.config就不赘述了,主要说说写入app.config.
据说微软不太建议我们动态写入app.config的,但是不可避免的有人因为业务或其他需要就非要写入app.config.
其实app.config就是个xml文件,找到位置,读出来,改了,然后保存回去,就行了。
重要一点:app.config运行时就不在原来的目录下了,名称也变了。所以在写入时一定要写运行时那个文件.
代码如下:
 

        /**/ /// <summary>
        
/// 设置app.config中的某个key的value.
        
/// </summary>
        
/// <param name="AppKey">key</param>
        
/// <param name="AppValue">value</param>

         public    void   SetValue( string  AppKey,  string  AppValue)
        
{
            XmlDocument xDoc 
= new XmlDocument();

            
//此处配置文件在程序目录下
            xDoc.Load(Application.StartupPath + "file://MailSender.exe.config/");
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode 
= xDoc.SelectSingleNode("//appSettings");
            xElem1 
= (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            
if (xElem1 != null)
            
{
                xElem1.SetAttribute(
"value", AppValue);
            }

            
else
            
{
                xElem2 
= xDoc.CreateElement("add");
                xElem2.SetAttribute(
"key", AppKey);
                xElem2.SetAttribute(
"value", AppValue);
                xNode.AppendChild(xElem2);
            }

            xDoc.Save(Application.StartupPath 
+ "file://MailSender.exe.config/");
        }


 

 

其实挺简单的,大家用时只需要把那个MailSender.exe.config改成自己的就行了(ProjectName.exe.config),编译后去debug里找一般都能找到.哈哈
备注:代码大部分来自网络,其它是自己的心得.谢谢大家支持.

转载于:https://www.cnblogs.com/GodSpeed/archive/2008/05/13/1195488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值