Configuration files

By   Calendar icon Aug 11, 2019   Level 1 icon

Description:

In this article, we explain how to make a simple configuration file in XML language in C#. Such a file is used to back up certain parameters of a program.

Preferencesoft

Tags: C#

This article offers a simple way to save the settings for an application when it has few parameters.

Text, INI, XML files

A developer can always save the parameters of its application in a simple text file by converting its data to character strings beforehand. But this solution can be complicated when retrieving the values of parameters or when changing certain parameters during programming. On Windows, application configuration files are traditionally INI files. They are divided into sections whose name is enclosed in brackets. Inside a section, parameters are associated with a value by a = symbol:
<parameter>=<value>

Functions are available to the developer for easy access to the parameters and their value. But the INI file management libraries are not available for any type of application. Some developers recommend the use of file in XML format instead of the INI files. The structure of a XML file being a tree, it allows to emulate that of an INI file.

XML configuration files

So, we will use a file in XML format to save the configuration settings. But unlike the INI files, let us not create section. When an application has few configuration variables, can simply place all the parameters at the root of the XML file, i.e. in a single root node.

Now write a class in C# managing configuration files. In this class, declare the following methods:

  • Open opens the file
  • close closes the file (recording data)
  • SetValue records a parameter followed by its value
  • GetValue Gets the value of a parameter
class XmlConfig
{
    XmlDocument doc = new XmlDocument();
    string file_name = "";
    public XmlConfig(string name)
    {
        file_name = name;
    }

    public void Open()
    {
        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        string pathAppData = localFolder.Path;

        using (FileStream fs = new FileStream(Path.Combine(pathAppData, file_name + ".xml"), FileMode.OpenOrCreate))
        {
            try
            {
                doc.Load(fs);
                //fs.Flush();
                fs.Dispose();
            }
            catch (Exception)
            {
                doc.LoadXml("<root></root>");
            }
        }
    }

    public void Save()
    {
        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        string pathAppData = localFolder.Path;

        using (FileStream fs = new FileStream(Path.Combine(pathAppData, file_name + ".xml"), FileMode.Create))
        {
            doc.Save(fs);
            fs.Flush();
        }
    }


    public void SetValue(string entry, string value)
    {
        XmlElement elementRoot = doc.DocumentElement;
        XmlNodeList lstTitles = doc.GetElementsByTagName(entry);
        int n = lstTitles.Count;
        if (n > 0)
        {
            XmlElement element = (XmlElement)lstTitles.Item(n - 1);
            element.InnerText = value;
        }
        else
        {
            XmlElement element = doc.CreateElement(entry);
            elementRoot.AppendChild(element);
            XmlText txtCatetory = doc.CreateTextNode(value);
            elementRoot.LastChild.AppendChild(txtCatetory);
        }
    }

    string GetValue(string entry)
    {
        XmlNodeList listEntries = doc.GetElementsByTagName(entry);
        int n = listEntries.Count;
        if (n > 0)
        {
            XmlElement element = (XmlElement)listEntries.Item(n - 1);
            return element.InnerText;
        }
        else
        {
            return "0";
        }
    }

    public void RemoveParameter(string entry)
    {
        XmlElement elementRoot = doc.DocumentElement;
        XmlNodeList listEntries = doc.GetElementsByTagName(entry);
        int n = listEntries.Count;
        if (n > 0)
        {
            elementRoot.RemoveChild(listEntries.Item(n - 1));
        }
    }
}
and the call:
private async void button_Click(object sender, RoutedEventArgs e)
{
    XmlConfig xc = new XmlConfig("configfile");
    xc.Open();
    xc.SetValue("ccccc","4545");
    xc.SetValue("ddddd", "++++");
    xc.RemoveParameter("ddddd");
    xc.Save();
}

CSharp