September 4, 2015

Loading application settings from a custom configuration file

Here is a unit test to show how to load configuration data from a custom configuration file (useful in unit tests)
private string configContents =
 @"<?xml version='1.0' encoding='utf-8'?>" +
 @"<configuration>" +
 @"  <startup>" +
 @"    <supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2'/>" +
 @"  </startup>" +
 @"  <appSettings>" +
 @"" +
 @"    <add key='intValue' value='42' />" +
 @"    <add key='stringValue' value='blah, blah, blah' />" +
 @"" +
 @"  </appSettings>" +
 @"</configuration>";

[Test]
public void RawCustomConfigTest()
{
 // Write out the test config file
 string exeDir = System.IO.Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath);
 string configPath = Path.Combine(exeDir, "Test.config");
 File.WriteAllText(configPath, configContents, Encoding.UTF8);

 // Read it in
 SysConfig.ExeConfigurationFileMap map = new SysConfig.ExeConfigurationFileMap { ExeConfigFilename = configPath };
 SysConfig.Configuration config = SysConfig.ConfigurationManager.OpenMappedExeConfiguration(map, SysConfig.ConfigurationUserLevel.None);
 var appSettings = config.AppSettings.Settings;

 // Read in the test entries
 string intValue = TryGetValue(appSettings, "intValue", "-1");
 string stringValue = TryGetValue(appSettings, "stringValue", "");
 string otherValue = TryGetValue(appSettings, "DoesNotExistInConfig", "not present"); // does not exist in the config file

 // Show that it worked
 Assert.That(intValue == "42");
 Assert.That(stringValue == "blah, blah, blah");
 Assert.That(otherValue == "not present");
}

private static string TryGetValue(SysConfig.KeyValueConfigurationCollection appSettings, string name, string defaultValue)
{
 try
 {
  return appSettings[name].Value;
 }
 catch (NullReferenceException)
 {
  return defaultValue;
 }
}

No comments: