Web.config Settings and Event Handlers

Author by Mark Rentmeester

Have you ever wanted to gain access to the SharePoint Web.config file to pull in some AppSettings within a SharePoint event handler? Perhaps within your Feature Activating Event, or maybe an Item Added Event? You may have tried something like this:
using System.Configuration; string MyValue = ConfigurationManager.AppSettings["MyKey"].ToString();
...And you would've noticed that although your code compiles and runs, this comes back null. How nice. Well, the very generic answer to why this is, is because the event handler isn't really running within the same context as a Web site that has direct access to the ConfigurationManager. Regardless, we still need to access the Web.config! How? Like this...
public static string GetAppSetting(SPSite site, string key) { if (string.IsNullOrEmpty(site.WebApplication.Name)) throw new ApplicationException("Web Application Name was found empty.");Configuration config = WebConfigurationManager.OpenWebConfiguration("/", site.WebApplication.Name); AppSettingsSection appSettings = config.AppSettings; if (appSettings == null || string.IsNullOrEmpty(appSettings.Settings[key].Value)) throw new ApplicationException("Cannot read value with supplied key. Does " + key + " exist?"); else return appSettings.Settings[key].Value.ToString(); }   This article was originally written by Jordan Laik. It is moderated currently by Mark Rentmeester.

Mark Rentmeester

Director of Application Development Services