web.config中存在检查设置

时间:2016-09-26 13:55:17

标签: c# .net wcf web-config

如何检查web.config文件中是否存在设置?

我找到了以下代码,但我认为它是针对app.config文件的?我的设置在web.config中的位置。即使有6个,下面的代码也不返回任何键。

 if (ConfigurationManager.AppSettings.AllKeys.Contains(settingName))
 {
     return 1;
 }
 else
 {
      return 0;
 }

web.config中的示例设置:

<configuration>
  . . .
  <applicationSettings>
    <ProjectNameSpace.Properties.Settings>
    <setting name="mySetting" serializeAs="String">
       <value>True</value>
     </setting>
   </ProjectNameSpace.Properties.Settings>
  </applicationSettings>
</configuration>

最初我试图将其读出来,并检查它是否存在错误或存在。

 var property = Properties.Settings.Default.Properties[settingName];

但是这行代码似乎是从web.config加载的,如果它不存在,它会从项目设置中获取它。所以我不能通过检查值是否为空来判断它是否在web.config中,因为它被设置为其他东西!

4 个答案:

答案 0 :(得分:1)

也许你可以试试:

if (ConfigurationManager.AppSettings[name] != null)
{
    //The value exists
}

答案 1 :(得分:1)

如何将设计时间值设置为空值?

if(string.IsNullOrEmpty(Properties.Settings.Default.mySetting))
{
  // not set in web.config 
}
else
{
 // set in web.config and use it
}

Noe,如果您在web.config中设置了一个值,稍后在打开项目的设置文件时,它会尝试同步该值以匹配web.config值。

答案 2 :(得分:0)

以下适用于我。经过多次试验和错误。

使用上面的答案作为基础,将属性中的参数设置为空白。不要让它们从配置中自动更新。

然后使用类似的代码来检查值是否为空。它还允许默认设置为值的布尔值等,因为它们不能为空。

您可以相应地调整它以检查特定设置,因为设置名称在foreach中可用。或者使用["settingname"]

它适用于布尔值和字符串设置。可能更多。它检查没有使用默认值(因为未找到值),如果没有,则检查包含的值。

    public int CheckSettings()
    {
        int settings = 0;

        SettingsPropertyValueCollection settingsval = Properties.Settings.Default.PropertyValues;

        foreach (SettingsPropertyValue val in settingsval)
        {
            settings += val.UsingDefaultValue || String.IsNullOrWhiteSpace((string)val.SerializedValue) ? 0 : 1;
        }

        return settings;
    }

答案 3 :(得分:0)

对于WPF桌面应用程序,我将执行以下操作:

if (Settings.Default.Properties[column.ColumnName] != null)
{
   //code                
}