Search This Blog

Friday, March 2, 2012

How to read Web.Config Values in Sharepoint

A typical Sharepoint Site consists of some site collections, sub sites. Since the root web is also a site collection, so in our SharePoint context, we cannot retrieve the web configuration <AppKeys> values directly from the SPWeb or SPWeb.RootWeb. Instead we will need to create an instance of Configuration from our WebApplication. I have written a simple method that you can use to read app keys that you put in the web.config of your Sharepoint site in any of the sub-site inside that web application.

-->
        /// <summary>
        /// GetConfigValueByKey
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="webApp"></param>
        /// <returns></returns>
        public static string GetConfigValueByKey(string Key, SPWebApplication webApp)
        {
            //required for getting config val from web app
            String strVal = String.Empty;
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApp.Name);
            if (config.AppSettings.Settings[Key] != null)
            {
                strVal = config.AppSettings.Settings[Key].Value;
            }
            return strVal;
        }

You will need to use the following namespace in your class: 
 
-->
using System.Configuration;

No comments:

Post a Comment