Проблема ConfigurationManager в VS 2017

Следующий код при запуске в 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);

person Mike Cheel    schedule 08.03.2017    source источник


Ответы (1)


Процесс размещения отладчика имеет Favorite-job.aspx" rel="nofollow noreferrer">был удален в VS2017, поэтому при запуске приложения путь, который вы указываете методу OpenExeConfiguration, неверен.

Вместо этого передайте Application.ExecutablePath этому методу, и он должен работать. То же самое должно работать в VS 2015, если вы отключите процесс размещения (Свойства проекта -> Отладка -> Включить процесс размещения Visual Studio).

Странно, что вы изначально использовали путь к хост-процессу, так как он будет работать только при запуске в отладчике из Visual Studio.

person adrianbanks    schedule 08.03.2017
comment
Странность в том, что у меня есть код-заглушка, который позволяет мне переключаться между различными средами, и мое приложение считывает различные настройки, чтобы определить, куда подключаться и под каким именем регистрироваться. Это экономит время на настройку всего этого вручную, так как мне нужно часто переключаться между ними. - person Mike Cheel; 08.03.2017