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:
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)
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?");
This article was originally written by Jordan Laik. It is moderated currently by Mark Rentmeester.