My question is not about how to update an application's config file
during
run-time, but how to invalidate the cached copy so that if a change to
the
config file is made, the application can use the new data without being
restarted.
Is there a programmatic way to invalidate the cached copy of an
app.config
file?
In the "old" .INI file days, there was a work-around to this caching. How
do we do it today?
Help is appreciated.
It's not a huge deal. This implementation is cut down from a live class:
using System;
using System.Configuration;
using System.Xml;
using System.IO;
using System.Reflection;
namespace Xyz {
/// <summary>
/// Checks whether the private config specified needs to be reloaded
and does so /// </summary>
public class PrivateConfig {
private PrivateConfig() {
}
private static XmlDocument configDoc;
private static DateTime dateTimeOfLoadedFile;
private static XmlNode translations;
private static object lockWithThis = new object();
public static bool IsStale {
get {
bool isStale = false;
if (configDoc == null) {
isStale = true;
} else {
// Check file load time
string configPath =
ConfigurationSettings.AppSettings["ConfigurationFile"];
FileInfo fi = new FileInfo(configPath);
if (fi.LastWriteTime > dateTimeOfLoadedFile) {
isStale = true;
}
}
return isStale;
}
}
public static XmlDocument Load() {
if (PrivateConfig.IsStale) {
string configPath =
ConfigurationSettings.AppSettings["ConfigurationFile"];
lock(lockWithThis) {
FileInfo fi = new FileInfo(configPath);
if (fi.LastWriteTime > dateTimeOfLoadedFile) {
configDoc = new XmlDocument();
configDoc.Load(fi.FullName);
translations = null;
dateTimeOfLoadedFile = fi.LastWriteTime;
}
}
}
return configDoc;
}
public static string Value(string key) {
PrivateConfig.Load();
XmlNode node = configDoc.SelectSingleNode("descendant::" + key);
string retVal = "";
if (node != null) {
retVal = node.InnerText;
}
return retVal;
}
public static XmlNode Contents(string pathName) {
PrivateConfig.Load();
XmlNode contents = configDoc.SelectSingleNode("descendant::" +
pathName);
return contents;
}
public static bool IsSet(string setting) {
PrivateConfig.Load();
XmlNode node = configDoc.SelectSingleNode("descendant::" + setting);
bool retVal = false;
if (node != null) {
string text = node.InnerText.ToLower();
if (text == "true" || text == "1") {
retVal = true;
}
}
return retVal;
}
}
}
Simon Smith
simon dot s at ghytred dot com
www.ghytred.com/NewsLook - NNTP Client for Outlook