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里找一般都能找到.哈哈
备注:代码大部分来自网络,其它是自己的心得.谢谢大家支持.

posted @ 2008-05-13 17:21  GodSpeed  阅读(4164)  评论(1编辑  收藏  举报