Configuration类在网页实现对web.config的修改[转]

本文详细探讨了.NET Framework中ConfigurationManager.OpenExeConfiguration的使用误区,指出其不能直接打开并修改配置文件,并通过实例展示了如何正确地进行配置文件的读取与写入操作。

【IT168技术文档】 

  一、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"));

  操作,则确实实现了对文件的修改。

 

【原地址】:http://tech.sina.com.cn/s/2008-06-30/1013712947.shtml

转载于:https://www.cnblogs.com/yongtaiyu/p/3594182.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值