Wrapping System.Configuration.ConfigurationManager.AppSettings[KeyName] call

if you currently using

System.Configuration.ConfigurationManager.AppSettings[KeyName];

to get the stored asp.net application configurations ,you should check the return value against null value because this method will return null incase this key doesn't exists and you will get a null reference exception if you trying to access this value ... so it's better to wrap this call by a small utility function to throw a meaningfully exception instead of null to prevent the 'null reference exception' which will be more helpful in the deployment scenarios.

here is a small sample :

   1: public static string GetKey(string keyName)
   2:        {
   3:            if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null)
   4:                return System.Configuration.ConfigurationManager.AppSettings[keyName].ToString();
   5:            else
   6:                throw new ArgumentException("a key with the name " + keyName + " doesn't exists in the current configurations", keyName);
   7:        }

5 Comments

  • I wrap all my config calls in a Config class. The main advantage being I get intellisense, but also compile time checking if I were to yank a config item out.

  • I agreed with you that it is a good idea to do so … Thanks a lot for your feedback.

  • Im trying to You get passed back an attribute name key-based list (or IDictionary) of objects, which you then need to cast into strings:


    param = (System.Collections.IDictionary)System.Configuration.ConfigurationManager.GetSection("tableManager");


    and im geting an error
    The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration' (are you missing an assembly reference?


  • I think it's better to implement your own class which inherit form ConfigurationSection and contains tableManager data like the below example http://aspalliance.com/articleViewer.aspx?aId=924&pId=-1

  • I was geting this error as well, i had to explicitly add System.configuration to my project's referances, then the name space came up in intellisense.

Comments have been disabled for this content.