没有从Vista中的machine.config读取appSettings

Chr*_*ett 6 vista64 .net-2.0 winforms machine.config

我最近升级到Vista x64,突然之间,任何.NET程序集都没有读取我的machine.config appSettings块.

在configSections之后,在C:\ Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config中的configProtectedData之前,我有:

<appSettings>
    <add key="foo" value="blah"/>
</appSettings>
<system.runtime.remoting>
    <customErrors mode="Off"/>
</system.runtime.remoting>
Run Code Online (Sandbox Code Playgroud)

不得不通过以管理员身份运行Notepad ++来保存它,因为它被锁定,否则可能是有充分理由的.在SnippetCompiler或VS .NET 2008中运行以下代码:

    foreach(var s in ConfigurationManager.AppSettings.AllKeys)
    {
        Console.WriteLine(s);   
    }

    AppSettingsReader asr = new AppSettingsReader();

    Console.WriteLine(asr.GetValue("foo", typeof(string)));
Run Code Online (Sandbox Code Playgroud)

写出没有密钥并因以下异常而失败:

---
The following error occurred while executing the snippet:
System.InvalidOperationException: The key 'foo' does not exist in the appSettings configuration section.
    at System.Configuration.AppSettingsReader.GetValue(String key, Type type)
    at MyClass.RunSnippet()
    at MyClass.Main()
---
Run Code Online (Sandbox Code Playgroud)

我编写的应用程序使用machine.config作为回退,用于找出用户应该在哪个环境中运行,如果在app.config中找不到它,那么我想避免重写我的应用程序来弄清楚应该像2000年和XP一样工作的东西.

Chr*_*ett 8

用以下代码行解决了它:

ConfigurationManager.OpenMachineConfiguration().FilePath
Run Code Online (Sandbox Code Playgroud)

返回:

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Config\machine.config
Run Code Online (Sandbox Code Playgroud)

代替:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config
Run Code Online (Sandbox Code Playgroud)

忘了我现在用的是64位.在正确的配置文件中添加appSettings部分解决了这个问题.