我用C#在VS2003下开发WINFORM程序,以下为我的APP.CONFIG文件,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
      <add key="ConnectionString" value="data source=nts1;initial catalog=Card;persist security info=False;user id=sa;" />
      <add key="ConnectionString1" value="data source=nts1;initial catalog=CardHistory;persist security info=False;user id=sa;" />
      
      <add key="opId" value="1" />
      <add key="opName" value="管理员" />
            
</appSettings>
</configuration>
............................................
如何在进入我的系统时将<add key="opId" value="1" />
      <add key="opName" value="管理员" />
改为<add key="opId" value="2" />
      <add key="opName" value="张三" />先谢谢了!!!!!

解决方案 »

  1.   

    private void AppSettingsEdit(string ConfigDirectory,string appSettingsAddkey,string keyvalue)
    {
    try
    {
    string path=ConfigDirectory+"\\app.config";
    XmlDocument xd=new XmlDocument();
    xd.Load(path); //如果没有appSetting,则添加
    if(xd.SelectNodes("//appSettings").Count==0)
    {
    xd.DocumentElement.AppendChild(xd.CreateElement("appSettings"));
    } //判断节点是否存在,如果存在则修改当前节点
    bool addNode=true;
    foreach(XmlNode xn1 in xd.SelectNodes("/configuration/appSettings/add"))
    {
    if(xn1.Attributes["key"].Value==appSettingsAddkey)
    {
    addNode=false;
    xn1.Attributes["value"].Value=keyvalue;
    //      xn1.ParentNode.RemoveChild(xn1);
    break;
    }
    } //当前节点不存在,则添加新节点
    if(addNode)
    {
    //创建新节点
    XmlNode xn2=xd.CreateElement("add"); //添加key
    XmlAttribute xa=xd.CreateAttribute("key");
    xa.Value=appSettingsAddkey;
    xn2.Attributes.Append(xa); //添加value
    xa=xd.CreateAttribute("value");
    xa.Value=keyvalue;
    xn2.Attributes.Append(xa);
    xd.SelectSingleNode("/configuration/appSettings").AppendChild(xn2);
    }
    //保存web.config
    xd.Save(path);
    //return true;
    }
    catch
    {
    //return false;
    throw new Exception("error");
    }
    }
      

  2.   

    1.1版没有直接修改app.config的类库,需要把它加载到dom进行修改,
    xmldocument对象中操作,
    好像2.0版本提供了ConfigurationManager来进行管理,