来自Asp.net精英论坛:bbs.1aspx.com
网上有好多关于自己解析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);
= 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();
= 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>
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"));
= 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吧,呵呵