以下代码在Visual Studio 2015及更早版本中运行时,会显示一个消息框,并显示期望值“12345”。VS 2017中的ConfigurationManager问题
string executablePath = Application.ExecutablePath;
executablePath = Path.GetFileNameWithoutExtension(executablePath);
executablePath = executablePath + ".vshost.exe";
if (!File.Exists(executablePath))
throw new FileNotFoundException(executablePath);
Configuration cfg = ConfigurationManager.OpenExeConfiguration(executablePath);
cfg.AppSettings.Settings.Add("Testing", "12345");
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(cfg.AppSettings.SectionInformation.Name);
string testing = ConfigurationManager.AppSettings["Testing"];
MessageBox.Show(testing);
当我在Visual Studio 2017中运行相同的代码时,消息框显示空白值。
这是Visual Studio 2017中的错误还是代码需要修改?
UPDATE(具体原因):
所以主因,与公认的答案,却发生了,我已经打开了2015年VS,使产生的* .vshost.exe相关文件的解决方案。后来我在VS 2017中打开了解决方案,当然,* .vshost.exe文件不会自动清理,所以仍然存在。
更新2(对于那些谁希望能够在这两个使用类似的代码):
string executablePath = Application.ExecutablePath;
executablePath = Path.GetFileNameWithoutExtension(executablePath);
executablePath = executablePath + ".vshost.exe";
// Check if the *.vshost.exe exists
if (File.Exists(executablePath))
{
try
{
// If deleting throws an exception then the stub is being run by *.vshost.exe while
// debugging which means this is NOT Visual Studio 2017 (*.vshost.exe is no longer used in VS 2017)
File.Delete(executablePath);
// If it deletes then use the regular app path since VS2017 is using that now.
executablePath = Application.ExecutablePath;
}
catch (Exception)
{
executablePath = Application.ExecutablePath;
}
}
else
executablePath = Application.ExecutablePath;
Configuration cfg = ConfigurationManager.OpenExeConfiguration(executablePath);
cfg.AppSettings.Settings.Add("Testing", "12345");
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(cfg.AppSettings.SectionInformation.Name);
string testing = ConfigurationManager.AppSettings["Testing"];
MessageBox.Show(testing);
奇怪的是我有存根代码,允许我在各种环境之间切换,并且我的应用程序可以在各种设置中读取以确定连接的位置以及登录身份。这样可以节省时间,因为我需要频繁地在它们之间切换,所以必须手动配置所有这些。 –