VS 2017中的ConfigurationManager问题

时间:2017-03-08 20:09:12

标签: visual-studio-2017 configurationmanager

以下代码在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);

1 个答案:

答案 0 :(得分:0)

调试器托管过程有been removed in VS2017,因此当您运行应用程序时,您为OpenExeConfiguration方法提供的路径不正确。

相反,将Application.ExecutablePath传递给该方法,它应该有效。如果您关闭托管过程(项目属性 - >调试 - >启用Visual Studio托管过程),这在VS 2015中也应该有效。

您首先使用托管进程路径很奇怪,因为只有在Visual Studio中从调试器运行时才会有效。