UP,能行么?要不用INI文件也行的

解决方案 »

  1.   

    我把服务器的数据库连接配置放到config文件中,但是在客户首次运行的时候,要对这些参数进行设置,那么,我应该如何去读取和修改这些值哟?
      现在读取的方法很简单,但是如何修改呢?
      还有,在运行的时候,可以修改通过应用程序本身修改应用程序的config文件吗? 
      

  2.   

    修改WEB.CONFIG文件的函数: public void ModifyConfigSet(string ConfigFileName,string strKey,string strValue)
    { ///  修改指定config文件appSettings配置节中的Add里的value属性
    /// </summary>
    /// <res>
    ///  注意,调用该函数后,会使整个Web Application重启,导致当前所有的会话丢失
    /// </res>
    /// <param name="key">要修改的键key</param>
    /// <param name="strValue">修改后的value</param>
    /// <exception cref="">找不到相关的键</exception>
    /// <exception cref="">权限不够,无法保存到web.config文件中</exception>
    /// 
    string XPath="/configuration/appSettings/add[@key='?']";
    XmlDocument domWebConfig=new XmlDocument();
       
    domWebConfig.Load( (HttpContext.Current.Server.MapPath(ConfigFileName)) );
    XmlNode addKey=domWebConfig.SelectSingleNode( (XPath.Replace("?",strKey)) );
    if(addKey == null)
    {//如果没找到,就新加一条
    this.InsertConfigSet(ConfigFileName,strKey,strValue);
    return;
    }
    addKey.Attributes["value"].InnerText=strValue;
    domWebConfig.Save( (HttpContext.Current.Server.MapPath(ConfigFileName)) );
       
    }
      

  3.   

    在Web.config中新加一行的函数:
    public void InsertConfigSet(string ConfigFileName,string strKey,string strValue)
    {   //向指定config文件中插入节点和设置值
    string XPath="/configuration/appSettings";
    XmlDocument domWebConfig=new XmlDocument(); domWebConfig.Load( (HttpContext.Current.Server.MapPath(ConfigFileName)) );
    XmlNode appSettings=domWebConfig.SelectSingleNode( XPath );
    XmlNode add= domWebConfig.CreateNode(XmlNodeType.Element,"add",""); XmlAttribute key=domWebConfig.CreateAttribute("key");
    key.Value=strKey;
    XmlAttribute Value=domWebConfig.CreateAttribute("value");
    Value.Value=strValue; add.Attributes.Append(key);
    add.Attributes.Append(Value); appSettings.AppendChild(add); domWebConfig.Save( (HttpContext.Current.Server.MapPath(ConfigFileName)) );
    }
      

  4.   

    调用示例:this.ModifyConfigSet("Web.Config",strKey,strValue);strKey为你想改的键名,strValue为新的值。