在运行时更新 app.config system.net 设置 [英] Update app.config system.net setting at runtime

查看:34
本文介绍了在运行时更新 app.config system.net 设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时更新 .Net exe app.config 文件的 system.net SectionGroup 中的设置.我在运行时没有对原始配置文件的写访问权限(我正在开发一个 .Net dll 加载项,它托管在我无法控制的应用程序提供的 exe 中)所以我希望保存一个副本并在运行时用修改后的版本替换 exe 中的配置.我已经尝试了以下但它不起作用.有什么建议吗?

I need to update a setting in the system.net SectionGroup of a .Net exe app.config file at runtime. I don't have write access to the original config file at runtime (I am developing a .Net dll add-in which is hosted in an exe provided by the app which I have no control over) so I was hoping to save a copy of the file and replace the config in the exe with the modified version at runtime. I've tried the following but it's not working. Any suggestions?

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    NetSectionGroup netSectionGroup = config.GetSectionGroup("system.net") as NetSectionGroup;
    netSectionGroup.Settings.HttpWebRequest.UseUnsafeHeaderParsing = true;                      
    config.SaveAs(@"C:\ProgramData\test.config", ConfigurationSaveMode.Full);

    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\ProgramData\test.config");

推荐答案

我不明白您的问题是由于您自己的设计实现而无法访问 app.config 文件还是您无法访问保存配置文件,所以这里是一段代码,允许您在运行时修改和保存配置文件中的 appSettings 部分:

I did not understand from your question if you don't have access to the app.config file because of your own design implementation or you just weren't able to save the config file, so here is a piece of code that allows you to modify and save appSettings section in the config file at runtime:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;

// update SaveBeforeExit
settings[-keyname-].Value = "newkeyvalue";
...
//save the file
config.Save(ConfigurationSaveMode.Modified);
//relaod the section you modified
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

P.S 代码不会保存您在解决方案编辑器中看到的 app.config 文件,它会更新操作文件夹中的program_name.exe.config"文件.

P.S the code will not save the app.config file you see in the solution editor, it will pdate the "program_name.exe.config" file in the operation forlder.

这篇关于在运行时更新 app.config system.net 设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆