无法使用Properties.Settings从app.config中读取

时间:2015-02-04 10:33:21

标签: c# properties app-config

我正在尝试从我的AppConfig中读取,但它无效。

App.Config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <section name="Console.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
</configSections>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
    <Console.Properties.Settings>
        <setting name="LogFiles" serializeAs="String">
            <value>True</value>
        </setting>
    </Console.Properties.Settings>
</userSettings>
</configuration>

的Program.cs:

namespace Console
{
class Console
{
    public static readonly bool LogFiles = Properties.Settings. //Cant find symbol Default
    static void Main(string[] args)
    {
        //Do stuff here
    }
}
}

使用Properties.Settings时找不到默认符号或LogFiles属性。我错过了什么?

1 个答案:

答案 0 :(得分:3)

实现此目的的惯用方法是使用ConfigurationManager.AppSettings[key]代替。配置看起来像:

<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="LogFiles" value="True" />
  </appSettings>
</configuration>

应用程序设置的检索将是:

bool logFiles = Convert.ToBoolean(ConfigurationManager.AppSettings["LogFiles"]);