配置修改后写入错误文件:如何将变更写入原读取的配置文件?
问题原因与解决方案:配置修改写入错误文件
问题原因
你遇到的问题核心在于获取配置文件的方式不对:
你的代码是放在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
相关产品推荐
相关产品推荐

