This is a simple example of how to use xml serialization to make configuration files.
In many cases there is no need to use System.Configuration namespace members for application configuration file. This article will focus on XML serialization.
The main idea is to create class which holds configuration data and then, serialize it to a file using XmlSerializer. Classes that can be serialized using XML must be declared as public and have a parameterless constructor. Also serialized members must be public.
For more information about XML serialization please refer to http://msdn.microsoft.com/en-us/library/182eeyhh.aspx
To serialize and deserialize data use corresponding methods from XmlSerializer class (System.Xml.Serialization). Both of them operate on stream objects.
The following code sample demonstrates creating, reading and saving of simple configuration file.
using System;
using System.Xml.Serialization;
using System.IO;
namespace XMLconfigExample
{
class Program
{
static void Main(string[] args)
{
// get configuration
Config.ConfigData config = Config.GetConfigData();
// use it
Console.WriteLine(config.buffsize);
// change data
config.buffsize = 1024;
// save config
Config.SaveConfigData(config);
// test saved data
config = Config.GetConfigData();
Console.WriteLine(config.buffsize);
Console.ReadKey(true);
}
}
public class Config
{
#region Default Data
private const int DEF_BUFF_SIZE = 2048;
private const string DEF_LOCAL_GATE_IP = "192.168.2.2";
private const string DEF_TARGET_IP = "192.168.2.10";
private static readonly int[] DEF_PORTS = new int[] {
3500,
4500,
};
#endregion
// name of the .xml file
public static string CONFIG_FNAME = "config.xml";
eyal goltzmanPosted Jul 7, 2014, 4:39 PM
To over come that problem I changed the filestream file mode in the SaveConfigData function to FileMode.Truncate
eyal goltzmanPosted Jul 7, 2014, 4:38 PM
There is a problem in the above program - If the saved file is shorter then the original file the file get corrupted with the left over of the previous file version.