Следующий код при запуске в Visual Studio 2015 и более ранних версиях приводит к отображению окна сообщения с ожидаемым значением "12345".
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 или код требует модификации?
ОБНОВЛЕНИЕ (конкретная причина):
Таким образом, основная причина, наряду с принятым ответом, заключалась в том, что я открыл решение в VS 2015, которое сгенерировало файлы, связанные с * .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);