首页 > 解决方案 > 修改后的配置写入不同的 config.file

问题描述

我正在从 app.config 文件中读取值。在进行了一些更改后,我正在保存配置。问题是更改正在写入不同的文件。

正在从 GeoBagHostingService.exe.config 读取值。正在将更改写入 GeoBagService.dll.config

我的解决方案包含 2 个项目:GeoBagHostingService 和 GeoBagService,所以这可能是事情混淆的地方。

从功能上讲,我想做的是用加密值替换密码值。因此,如果配置包含“密码”密钥,我将其替换为包含加密密码值的“加密密码”密钥。

我正在使用的代码包含在 de GeoBAGService 项目的一个类中。

要读取、修改和保存我使用的配置:

// Opening the configuration (GeoBagHostingService.exe.config)
Configuration configuration = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);

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);

     // Writing back the changes (or so I thought)
     // encryptedPassword is now in GeoBagService.dll.config
     configuration.Save();
   }

else 
   { 
     oraclePassword = DecryptString(ConfigurationManager.AppSettings["encryptedpassword"], configPassword); 
   }

这里发生了什么以及如何将更改写入与读取位置相同的配置?

标签: c#app-config

解决方案


结果Assembly.GetExecutingAssembly().Location取决于您从哪里调用它。

如果您在主项目(应用程序)中调用它,那么它将返回:

[MainProjectPath]\[MainProjectName].exe

如果您从另一个项目(类库)调用它,那么它将返回:

[LibProjectPath]\[LibProjectName].dll

这就是为什么你会得到这些结果。


推荐阅读