【问题标题】:ASP.Net - How do I programatically edit external config files at runtimeASP.Net - 如何在运行时以编程方式编辑外部配置文件
【发布时间】:2011-03-01 14:31:10
【问题描述】:

外部配置文件是指 web.config 以外的 .config 文件。我已经看过有关如何在运行时编辑 web.config 的所有示例,但我想编辑 appSettings 的 configSource 引用的配置文件。我只想修改外部文件,我会处理应用回收。

理想情况下,我想使用内置类来处理编辑,但如果唯一的选择是手动文件打开/解析等,那么就这样吧。

这一切背后的总体思路是在应用启动时查看设置页面,用户设置他们的详细信息,然后保存更改,然后真正的应用启动。快速简便的安装应用程序/配置页面,所以我想尽可能利用 .config。

谢谢!

FOLLOWUP - 使用 XmlDocument 更改 appSetting 键值的快速片段:

string path = Server.MapPath("~/my.config");

XmlDocument doc = new XmlDocument();
doc.Load(path);

XmlNode node = doc.SelectSingleNode("/appSettings/add[@key='myKey']");
node.Attributes[1].Value = "myVal";

XmlTextWriter writer = new XmlTextWriter(path, null);
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
writer.Flush();
writer.Close();

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    编辑标准配置文件的常用代码如下:

    string cfgPath = Path.Combine(targetDir, "myApp.config");
    var configMap = new ExeConfigurationFileMap { ExeConfigFilename = cfgPath };
    
    var cf = ConfigurationManager.OpenMappedExeConfiguration(configMap,
        ConfigurationUserLevel.None);
    cf.AppSettings.Settings["somekey"].Value = "newvalue";
    
    cf.Save();
    

    顺便说一句,代码版本是 .NET 3.5。

    您可能还需要设置正确的权限。请注意,如果您没有标准配置文件布局(根节点为<configuration>),此代码将引发异常。

    【讨论】:

    • 这是一个很好的例子,但是由于外部配置文件没有 根节点,所以会抛出错误,使用 configSource 文件时根节点必须是 。
    • @Stuart:是的,你是对的,你需要一个 根节点。我假设您使用的是标准配置文件。
    • 之所以需要使用 是因​​为该文件在 web.config 中被引用为 configSource 属性。感谢您的及时帮助。
    【解决方案2】:

    您至少应该能够利用System.Xml Namespace 中的类来读取设置文件,就像读取任何旧的 XML 文件一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      相关资源
      最近更新 更多