ASP.Net - 如何在运行时以编程方式编辑外部配置文件

8
通过外部配置文件,我的意思是除web.config之外的.config文件。我已经看到了有关如何在运行时编辑web.config的所有示例,但我想编辑由configSource引用的配置文件用于appSettings。我只想修改外部文件,并且我将处理应用程序重新启动。
理想情况下,我想使用内置类来处理编辑,但如果唯一的选择是手动打开/解析文件等,则可以这样做。
所有这些背后的一般想法是一个设置页面,在应用程序启动时查看该页面,用户设置其详细信息,然后保存更改,然后真正的应用程序启动。快速简便的安装应用程序/配置页面,因此我希望尽可能利用.config。
谢谢!
跟进 - 使用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();
2个回答

7
通常编辑标准配置文件的代码如下所示:

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>),则此代码将抛出异常。


1
这是一个很好的例子,但会抛出错误,因为外部配置文件没有<configuration>根节点,当使用configSource文件时,根节点必须是<appSettings>。 - Stuart Allen
@Stuart:是的,你说得对,你需要有一个<configuration>根节点。我假设你正在使用标准配置文件。 - code4life
需要使用<appSettings>的原因是该文件被引用为web.config中的configSource属性。感谢您及时的帮助。 - Stuart Allen

1

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接