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

时间:2011-03-01 14:31:11

标签: c# asp.net

通过外部配置文件,我的意思是除web.config之外的.config文件。我已经看到了有关如何在运行时编辑web.config的所有示例,但我想编辑configSource为appSettings引用的配置文件。我想只修改外部文件,我将处理应用程序回收。

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

所有这一切背后的一般想法是在应用启动时查看的设置页面,用户设置他们的详细信息,然后保存更改,然后真正的应用程序启动。快速简便地安装app / configure页面,所以我想尽可能利用.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();

2 个答案:

答案 0 :(得分: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 :(得分:1)

您至少应该能够利用System.Xml Namespace中的类将设置文件读取为任何旧的XML文件。