gpt4 book ai didi

c# - 在运行时更新 app.config system.net 设置

转载 作者:IT王子 更新时间:2023-10-29 04:26:13 27 4
gpt4 key购买 nike

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

    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 部分:

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 文件,它会更新操作 forlder 中的“program_name.exe.config”文件。

关于c# - 在运行时更新 app.config system.net 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/980440/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com