检查设置存在于 web.config

Check setting exists in web.config

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

我找到了以下代码,但我认为它针对的是 app.config 文件?我的设置在 web.config 中。下面的代码 returns 即使有 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 中,因为它被设置为其他东西!

也许你可以试试:

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

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

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

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

以下适合我。经过反复试验。

以上述答案为基础,将属性中的参数设置为空白。不要让他们从配置中自动更新。

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

您可以相应地调整它以检查特定设置,因为设置名称在 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;
    }

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

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