1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ConfigurationManager.AppSettingsでキーがなかったらExceptionを発生させるクラスを書いてみた。

Posted at

COnfigurationManager.AppSettingsって指定したキーがなくてもnullが返答されるだけどエラーにはならんのです。

そのあと、そのConfigurationを使用した処理がエラーになるかも知れないし、意図してそう動いて欲しい時もあるんだけど、逆にエラーにしたい場面もあったりします。

そういうのを簡単に切り替えられるクラスってどんな感じかなぁって考えて書いてみました。


    public static class ConfigurationManagerRequired
    {
        static ConfigurationManagerRequired()
        {
            AppSettings = new AppSettingsRequired();
        }

        public static AppSettingsRequired AppSettings { get; }

        public class AppSettingsRequired
        {
            public string this[string keyName]
            {
                get
                {
                    if (ConfigurationManager.AppSettings.AllKeys.Contains(keyName))
                    {
                        var value = ConfigurationManager.AppSettings[keyName];
                        if (string.IsNullOrEmpty(value))
                        {
                            throw new Exception($"AppSettings key {keyName} is empty");
                        }

                        return value;
                    }
                    else
                    {
                        throw new Exception($"AppSettings key {keyName} is not found");
                    }
                }
            }
        }
    }

普通は



var value = ConfigurationManager.AppSettings["key"];

と取得できるのですが、キーを必須にしたい場合には


var value = ConfigurationManagerRequired.AppSettings["key"];

と書くと、キーが設定されていなかった場合にはExceptionが発生するようになります。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?