You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置修改后写入错误文件:如何将变更写入原读取的配置文件?

问题原因与解决方案:配置修改写入错误文件

问题原因

你遇到的问题核心在于获取配置文件的方式不对:
你的代码是放在GeoBagService.dll项目里的,当调用Assembly.GetExecutingAssembly().Location时,返回的是这个dll文件的路径,而不是主程序GeoBagHostingService.exe的路径。所以ConfigurationManager.OpenExeConfiguration()会基于这个dll路径,创建/修改对应的GeoBagService.dll.config文件,而不是你期望的GeoBagHostingService.exe.config。

简单说:代码运行在dll里,默认读取/写入的是dll的配置,而非主exe的配置。

解决方案

要解决这个问题,你需要获取当前应用域的主配置文件路径(也就是GeoBagHostingService.exe.config),而非当前dll的路径。这里推荐用AppDomain.CurrentDomain.SetupInformation.ConfigurationFile来获取,这个方法能可靠拿到当前运行环境的主配置文件路径,不管代码是在dll还是exe里都适用。

修改后的代码如下:

// 获取主应用程序的配置文件路径(GeoBagHostingService.exe.config)
string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
Configuration configuration = ConfigurationManager.OpenExeConfiguration(configPath);

var oraclePassword = ConfigurationManager.AppSettings["oraclePassword"];
if (!string.IsNullOrWhiteSpace(oraclePassword))
{
    string encryptedPassword = EncryptString(oraclePassword, configPassword);
    configuration.AppSettings.Settings.Remove("oraclePassword");
    configuration.AppSettings.Settings.Remove("encryptedPassword");
    configuration.AppSettings.Settings.Add("encryptedPassword", encryptedPassword);
    
    // 现在会写入到正确的主配置文件
    configuration.Save();
}
else
{
    oraclePassword = DecryptString(ConfigurationManager.AppSettings["encryptedpassword"], configPassword);
}

额外说明

  • 如果你确认主程序固定是GeoBagHostingService.exe,也可以用Process.GetCurrentProcess().MainModule.FileName获取主exe路径,再拼接.config后缀,但AppDomain的方法更通用,适配更多场景。
  • 若修改配置后需要立即生效,可调用ConfigurationManager.RefreshSection("appSettings")刷新配置缓存。

内容的提问来源于stack exchange,提问作者Rene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:02