Can code rot? Badness in System.Configuration.ConfigurationManager.OpenExeConfiguration

A while ago I wrote this article about how to use an alternative app.config source, ie when more apps need to share the same settings. I would normally pride myself of not writing about untested code, so I just couldn’t understand why the code I had written about didn’t seem to work in my app anymore. Was it beacuse it never worked, or had someting else changed?

When I ran the code, the OpenExeConfiguration just returned a null collection. I know that it read the file and that the syntax was ok, because otherwise the method would fail. Very puzzling indeed. Anyway, after much googling I found an alternative solution which I’ll show here:

// - new code begin -
 var filemap = new System.Configuration.ExeConfigurationFileMap();
 filemap.ExeConfigFilename = configFile;

 var config = System.Configuration.ConfigurationManager.
     OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);

 var settings = config.AppSettings.Settings;
 // - new code end -

 NameValueCollection appsettings = new NameValueCollection();
 foreach (var key in settings.AllKeys) appsettings.Add(key,settings[key].Value);

Was it only the HAL 9000 in the movie “2001” that had a mind of its own? Doesn’t always seem like it, and I can almost hear my code say “Sorry Dave, I can’t do that”…