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

Stu*_*len 7 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();
Run Code Online (Sandbox Code Playgroud)

cod*_*ife 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();
Run Code Online (Sandbox Code Playgroud)

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

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


Tom*_*han 1

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