Three Config File Reading Examples
Here are three examples of config file reading. I couldn't easily find enough information in one place and the MSDN documentation wasn't obvious enough.
This is a very generic snippet that can be pasted in a winform app. It's not rocket science, but I'm sure it will save someone a little time.
Type 1 - Regular configuration file settings
Type 2 - Section that uses nodes and the IConfigurationSectionHandler interface
Type 3 – Section that uses attributes and a class that inherits from ConfigurationSection
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--
Helpful Articles and Documentation:
http://www.dotnetbips.com/displayarticle.aspx?id=127
http://msdn.microsoft.com/en-us/library/system.configuration.configuration.getsection
http://msdn.microsoft.com/en-us/library/system.configuration.configuration
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondeclaringcustomconfigurationsections.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcreatingnewsectionhandlers.asp
-->
<!--Must specify a group to layout nodes in the section and not just attributes.-->
<configSections>
<sectionGroup name="Type2">
<section name="Field1" type="MultiConfigSections.MultConfigurationSectionHandler2, MultiConfigSections"/>
<section name="Field2" type="MultiConfigSections.MultConfigurationSectionHandler2, MultiConfigSections"/>
<section name="Field3" type="MultiConfigSections.MultConfigurationSectionHandler2, MultiConfigSections"/>
</sectionGroup>
<section name="Type3" type="MultiConfigSections.MultConfigurationSectionHandler3, MultiConfigSections" />
</configSections>
<Type2>
<Field1>c:\File2.txt</Field1>
<Field2>1234</Field2>
<Field3>Whatever!!</Field3>
</Type2>
<Type3 FileLocation="c:\File3.txt" UserId="4321" SomethingElse="!!revetahW" />
<appSettings>
<add key="Field1" value="c:\File1.txt" />
<add key="UserId" value="9876" />
<add key="Field3" value="Etc..." />
</appSettings>
</configuration>
// Must add a reference to System.Configuration assembly for the project.
using System.Configuration;
namespace MultiConfigSections
{
public partial class MultiConfigSectionsForm : Form
{
public MultiConfigSectionsForm()
{
InitializeComponent();
}
/// <summary>
/// Basic setting retriever.
/// </summary>
private void btnGetSetting1_Click(object sender, EventArgs e)
{
txtFileLocation.Text = ConfigurationManager.AppSettings[SettingField.Field1.ToString()] as string;
txtUserId.Text = ConfigurationManager.AppSettings[SettingField.UserId.ToString()] as string;
txtSomethingElse.Text = ConfigurationManager.AppSettings[SettingField.Field3.ToString()] as string;
}
/// <summary>
/// Retrieve section with the section path.
/// </summary>
private void btnGetSettings2_Click(object sender, EventArgs e)
{
SettingType settingType = SettingType.Type2;
string fileLocation = GetImportSetting(settingType, SettingField.Field1);
string userId = GetImportSetting(settingType, SettingField.Field2);
string somethingElse = GetImportSetting(settingType, SettingField.Field3);
txtFileLocation.Text = fileLocation;
txtUserId.Text = userId;
txtSomethingElse.Text = somethingElse;
}
/// <summary>
/// Retrieve settings using the class in one call to the ConfigurationManager class.
/// </summary>
private void btnGetSettings3_Click(object sender, EventArgs e)
{
// Read a specific config file or just default to the current EXE.
// Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// multConfigurationSectionHandler = configuration.Sections[SettingType.Type2.ToString()] as MultConfigurationSectionHandler;
MultConfigurationSectionHandler3 multConfigurationSectionHandler2 = ConfigurationManager.GetSection(SettingType.Type3.ToString()) as MultConfigurationSectionHandler3;
if (null != multConfigurationSectionHandler2)
{
txtFileLocation.Text = multConfigurationSectionHandler2.FileLocation;
txtUserId.Text = multConfigurationSectionHandler2.UserId;
txtSomethingElse.Text = multConfigurationSectionHandler2.SomethingElse;
}
}
/// <summary>
/// Return a single setting.
/// </summary>
private string GetImportSetting(SettingType settingType, SettingField settingField)
{
string ret = string.Empty;
string sectionName = string.Format("{0}/{1}", settingType.ToString(), settingField.ToString());
// The .Net 1.1 Method:
// ret = ConfigurationSettings.GetConfig(sectionName) as string;
// The .Net 2.0 Method:
ret = ConfigurationManager.GetSection(sectionName) as string;
return ret;
}
}
/// <summary>
/// Group Types.
/// </summary>
public enum SettingType
{
Type2,
Type3,
}
/// <summary>
/// Field Types.
/// </summary>
public enum SettingField
{
Field1,
Field2,
Field3,
FileLocation,
UserId,
SomethingElse
}
/// <summary>
/// Configuration class. This cannot be an inner class.
/// </summary>
class MultConfigurationSectionHandler2 : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
object ret = null;
if (section.Name == SettingField.Field1.ToString() ||
section.Name == SettingField.Field2.ToString() ||
section.Name == SettingField.Field3.ToString())
ret = section.ChildNodes[0].Value;
return ret;
}
}
/// <summary>
/// Configuration class. This cannot be an inner class.
/// </summary>
class MultConfigurationSectionHandler3 : ConfigurationSection
{
[ConfigurationProperty("FileLocation")] // Must Match XML Case
public string FileLocation
{
get { return this["FileLocation"] as string; }
set { this["FileLocation"] = value; }
}
[ConfigurationProperty("UserId")]
public string UserId
{
get { return this["UserId"] as string; }
set { this["UserId"] = value; }
}
[ConfigurationProperty("SomethingElse")]
public string SomethingElse
{
get { return this["SomethingElse"] as string; }
set { this["SomethingElse"] = value; }
}
}
}