Using ConfigurationManager.RefreshSection method in .NET 2.0.

Using ConfigurationManager.RefreshSection method in .NET 2.0.

by Steve Schofield

Download the application

This article shows how to update an application config file and have the new settings
take affect without stopping and starting a Windows .NET service.  This uses
the System.IO.FileSystemWatcher class in .NET 2.0.  This was not easy in .NET 1.0 or .NET 1.1
but only requires a couple lines of code in .NET 2.0.  My “hello world” application monitors a website
on a periodic basis and record the results to the Event Log, Database or sends an email
You can download the code to see how I implemented this in my application.  I’ve included the Setup project to install the application. 

Here is the code that refreshes the ‘appSettings’ section.

protected void fsw_Changed(object sender, System.IO.FileSystemEventArgs e)
{
         System.Diagnostics.EventLog.WriteEntry(“Application”,”FileChanged:” + e.Name);
         ConfigurationManager.RefreshSection(“appSettings”);
         LoadConfig();
}

To test this out, install the application on your machine and start the ‘AWebMonitorServiceCS’ service. 
After the service is running, change the URL setting to a different URL.  After so many seconds,
that is configured in the ‘Interval’ appSetting this will record the data in the Event Log.  
There will also be entries in the event log showing the ‘awebmonitorserviceCS.exe.config’ has changed. 

Sample event log text when the file changed

The description for Event ID ( 0 ) in Source ( Application ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: FileChanged:AWebMonitorServiceCS.exe.config.

Sample event log text what URL is being monitored

The description for Event ID ( 0 ) in Source ( Application ) cannot be found. The local computer may not
have the necessary registry information or message DLL files to display messages from a remote computer.
You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.
The following information is part of the event:
http://www.aspdot.net.

Good luck!

Steve