Get web.config file in timer job

I was working on timer job & wanted to get data from sql server. To achive this goal, I add my database connection string in web application’s web.config file.

Now I used the following code to get web.config setting from timer job :

private string getConnectionString()
        {
            return System.Configuration.ConfigurationManager.AppSettings["MyAppSettingKey"];     
  }

But this code was not able to get the web.config file.

Why?

I started some R & D on it & found that Time Job runs under OWSTimer.exe & Web Application runs under W3WP.exe. As the context of  Both are different so we have to use WebConfigurationManager to get specific SharePoint Web Application configuration.

private string getConnectionString(string webAppName)
        {
            System.Configuration.Configuration webConfiguration = WebConfigurationManager.OpenWebConfiguration("/", webAppName);

            return webConfiguration.AppSettings.Settings["MyAppSettingKey "].Value;
        }

This code is working in Timer Job.

Comments

Popular Posts

SharePoint Interview Questions and Answers

Download Infopath Form Templates

How to get current logged user information using JavaScript ?

Steps to set Form based authentication (FBA) for SharePoint 2010

SharePoint Interview Questions and Answers II

Get List Items - JavaScript

Change Language for current user with JSOM in SharePoint Online

Cross Site List Rollup Web Part for SharePoint 2010

Hide Recently Modified Items

SharePoint 2010 CSS Chart