質問

いくつかの異なるテーマを使用できるページを作成し、各テーマに関する情報をweb.configに保存します。

新しいsectionGroupを作成してすべてをまとめて保存する、または単にすべてをappSettingsに入れる方が効率的ですか?

configSectionソリューション

<configSections>
    <sectionGroup name="SchedulerPage">
        <section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
        <section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
</configSections>
<SchedulerPage>
    <Themes>
        <add key="PI" value="PISchedulerForm"/>
        <add key="UB" value="UBSchedulerForm"/>
    </Themes>
</SchedulerPage>

configSectionの値にアクセスするには、次のコードを使用しています:

    NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
    String SchedulerTheme = themes["UB"];

appSettingsソリューション

<appSettings>
    <add key="PITheme" value="PISchedulerForm"/>
    <add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>

appSettingsの値にアクセスするには、このコードを使用しています

    String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
役に立ちましたか?

解決

より複雑な構成設定では、たとえば各セクションの役割を明確に定義するカスタム構成セクションを使用します

<appMonitoring enabled="true" smtpServer="xxx">
  <alertRecipients>
    <add name="me" email="me@me.com"/>
  </alertRecipient>
</appMonitoring>

構成クラスでは、プロパティを次のようなもので公開できます

public class MonitoringConfig : ConfigurationSection
{
  [ConfigurationProperty("smtp", IsRequired = true)]
  public string Smtp
  {
    get { return this["smtp"] as string; }
  }
  public static MonitoringConfig GetConfig()
  {
    return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig
  }
}

その後、コードから次の方法で構成プロパティにアクセスできます

string smtp = MonitoringConfig.GetConfig().Smtp;

他のヒント

効率の点で測定可能な差はありません。

AppSettingsは、名前と値のペアだけが必要な場合に最適です。

より複雑なものについては、カスタム構成セクションを作成する価値があります。

言及した例では、appSettingsを使用します。

ConfigurationManager.AppSettingsは、とにかくGetSection(&quot; appSettings&quot;)を呼び出すだけなので、パフォーマンスに違いはありません。すべてのキーを列挙する必要がある場合、カスタムセクションはすべてのappSettingsを列挙してキーのプレフィックスを探すよりも優れていますが、そうでない場合は、NameValueCollectionより複雑なものが必要でない限りappSettingsに固執する方が簡単です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top