65.9K
CodeProject is changing. Read more.
Home

A Low Maintenance XML Settings Mechanism

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Mar 14, 2015

CPOL
viewsIcon

9848

downloadIcon

106

An easy way to edit and exchange XML config settings

Introduction

I needed an easy way to edit and exchange the config settings of a Windows service using a Windows Forms application.

As the .NET settings are really a hassle to accomplish something like this, I decided to write a simple XML settings class and a "SettingsManager" class that uses XML serialization to write and read the settings to a .config file.

Using the Code

Only the Forms application (see the demo, VS2013) is included here, as discussing Windows services is out of the scope of this tip, and it is enough to demonstrate the principle.

The nice thing about the Form is that it does not need any editing when the XML Settings class has changed.
Reflection is used to extract the settings class straight into a grid:

this.bindingSource1.Clear();

// Convert mySettings to grid.
foreach (var prop in SettingsManager.mySettings.GetType().GetProperties())
{
    string propValue = prop.GetValue(SettingsManager.mySettings, null).ToString();
    this.bindingSource1.Add(new ProvItem { Name = prop.Name, Value = propValue });
}

dataGridView1.DataSource = this.bindingSource1;
dataGridView1.Columns[0].ReadOnly = true;

Points of Interest

Note: If you are using an obfuscator, you will probably need to exclude the settings Form from obfuscation.

The generated settings .config file can also be viewed and edited with a normal text editor, e.g. Notepad++.

Happy serializing!