我在作一个考试试统,希望把一个值写在WebConfig文件中以便读取和修改,可是怎么实现呢?望指教。

解决方案 »

  1.   

    Web.Config就是XML文件,用修改XML的方法来改。这是一个创建连接字串的例子:
    StringBuilder sb2 = new StringBuilder();
    sb2.Append("data source=");
    sb2.Append(temp1);
    sb2.Append(";");
    sb2.Append("initial catalog=");
    sb2.Append(temp2);
    sb2.Append(";persist security info=False;");
    sb2.Append("user id=");
    sb2.Append(temp3);
    sb2.Append(";");
    sb2.Append("pwd=");
    sb2.Append(temp4);
    sb2.Append(";packet size=4096");
    StringBuilder xmlpath = new StringBuilder();
    xmlpath.Append(filepath);
    xmlpath.Append("\\");
    xmlpath.Append("Web.config");
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlpath.ToString());   //加载Web.Config
    XmlElement elem=doc.DocumentElement;
    XmlElement newelem = doc.CreateElement ("appSettings");
        XmlElement elem1 = doc.CreateElement("add");
    XmlNodeList nodes = doc.SelectNodes("/configuration/appSettings/add");
    //连接字符串赋值                 foreach(XmlNode node in nodes)
    {
    switch (node.Attributes["key"].Value)
    {
    case "strConnection":
    node.Attributes["value"].Value = sb2.ToString();
    break;
    default:
    // Don't do anything
    break; 
    }
    }
    doc.Save(xmlpath.ToString());   //保存修改
    加一句,你是女的???
      

  2.   

    这个问题简单,给你看看连接字符串的简单例子
    //webConfig中加一个appSettings节点,此节点一定在根节点后加
    <configuration>
      <appSettings>
        <add key="conString" value="server=.;database=pubs;uid=sa;pwd=;"/>
      </appSettings>
    //省略
      .........
    </configuration>
    代码中就可以这样取得他的值
    ConfigurationSettings.AppSettings["conString"].ToString();
    应该比较简单吧?
      

  3.   

    关注
    http://blog.csdn.net/dudu8686/archive/2004/09/12/ChrToImages.aspx
      

  4.   

    XmlDocument xml=new XmlDocument();
    xml.Load("Web.config文件路径");
    foreach(XmlNode node in xml.selectnodes("configuration/appSettings/add"))
    {
       if(node.Attributes["key"].value=="")
         node.Attributes["value"].value="";
    }
      

  5.   

    补充  ConfigurationSettings这个类的命名空间
    using System.Configuration;