zoukankan      html  css  js  c++  java
  • Configuration类在网页实现对web.config的修改(可能是2.0一个bug)

    网上有好多关于自己解析xml文件来修改web.config的办法,这些暂且不说。
    我看的资料里也有用Configuration与ConfigurationManager.OpenExeConfiguration修改配置文件的方法。但是都讲的没头没尾的,真是搞不懂。可能他们都说的是应用程序吧。

    一、ConfigurationManager.OpenExeConfiguration的问题
    ConfigurationManager.OpenExeConfiguration有两个重载,
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)

    ConfigurationManager.OpenExeConfiguration(Server.MapPath("web.config"));

    经过实验我发现,在网上上,ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)不能使用,而Configuration和ConfigurationManager.OpenExeConfiguration其实不能直接对文件进行修改。

            Configuration cfg = ConfigurationManager.OpenExeConfiguration(Server.MapPath("web.config"));
            Response.Write(cfg.FilePath);

    你会发现以上代码输出的FilePath是F:\路径\Web\web.config.config 。打开的文件虽然看的是web.config,其实是另外一个文件web.config.config,虽然web.config.config并不存在。

    而进行以下操作
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(Server.MapPath("web.config"));
            cfg.AppSettings.Settings.Remove(
    "123");
            cfg.AppSettings.Settings.Add(
    "123","asdasd");
            cfg.Save()
    ;
    读不出web.config的内容,而实际上是读的web.config.config的内容。我们现在没这个文件,那么内容就是空的。保存之后,得到
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        
    <appSettings>
            
    <add key="123" value="asdasd" />
        
    </appSettings>
    </configuration>

    二、引出来的思路
    可以建立个
    文件web.config.config,作为web.config的副本。
    再次执行
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(Server.MapPath("web.config"));
            cfg.AppSettings.Settings.Remove(
    "123");
            cfg.AppSettings.Settings.Add(
    "123","asdasd");
            Response.Write(cfg.FilePath);
            cfg.SaveAs(Server.MapPath(
    "web.config"));
    操作,则确实实现了对文件的修改。

    这可能是.net 2.0的一个bug吧,呵呵

    http://www.cnblogs.com/birdshover
    谢平
    2006年10月16日
  • 相关阅读:
    中阶 d04.1 xml解析
    中阶 d04 xml 概念及使用
    中阶 d03.5 (正篇)完整的Dao 操作数据库
    中阶d03.4 JDBC_DAO
    中阶d03.3 JDBC_CURD_Util --- 使用 junit执行单元测试(增删改查)
    单元测试 junit
    idle中上传jar包并使用的方法
    intelij idea 和 eclipse 使用上的区别
    中阶d03.2 JDBC联合properties使用,通过读取本地配置文件为代码传递参数
    swift init 初始化
  • 原文地址:https://www.cnblogs.com/birdshover/p/530327.html
Copyright © 2011-2022 走看看