INI File Reader

In this tutorial we’re going to create a class that will allow us to read and get data from an .ini file in c#.

Prerequisite

INI file format

Ini file are used as settings files and they have a structure like this:

1[section1]
2name1 = value
3name2 = value
4
5[section2]
6name1 = value
7name2 = value

Ini file are subdivided into section, each of those have at least one key, and each key have a value.
[...] this identify a section, inside it you can write any name.
name1 = value name1 is the name of the key, value is the value of the key.
Every key is associated to the last section, and there can’t be multiple keys with the same name inside the same section.

We saw its structure, so now we can write the code to read it.
Create a new Windows Form project, and you’re ready to start 😄

The class(es)

To write the code of the class we are going to use some list and nested classes.
Nested classes are classes defined inside another class.
Add a new class to the project, then on top add:

1using System.IO

Now we’ll create the first class that will allow us to read an .ini file.

1public class INIFile
2{
3
4}

Inside this let’s add:

1public List<Section> sectionList = new List<Section>();

We’ll define the class Section later.
Then we add a function to read the file:

 1public void LoadINIFile(string fileName)
 2{
 3    string curSection = null;
 4    string curKey = null;
 5    string curValue = null;
 6    foreach (string line in File.ReadLines(fileName))
 7    {
 8        if (line.StartsWith("["))
 9        {
10            curSection = line.Substring(1, line.Length - 2);
11            if(GetSection(curSection) == null)
12            {
13                sectionList.Add(new Section() { sectionName = curSection });
14            }
15        }
16        else if (line.Contains("="))
17        {
18            curKey = line.Split(char.Parse("="))[0];
19            curValue = line.Split(char.Parse("="))[1];
20            GetSection(curSection).SetKeyValue(curKey.Trim(), curValue.Trim());
21        }
22    }
23}

Inside the foreach function it will read the file fileName line by line.
if (line.StartsWith("[")) if this is true then this is a section, if this section is not inside our list then we add it.
else if (line.Contains("=")) this is a line with a key and its value, so we split the string into 2 pices one before and one after the “=” then we add these to the Section object.
We called the Trim() function to eliminate any white spaces.

Inside this function we called some function that we didn’t make yet, so let’s add them:

 1public Section GetSection(string section)
 2{
 3    Section result = null;
 4    foreach(Section s in sectionList)
 5    {
 6        if(s.sectionName == section)
 7        {
 8            result = s;
 9        }
10    }
11    return result;
12}

This function allow us to find a section in our list, it will return null if it don’t find it.

Section Class

Now we can create the Section class, so let’s add it inside the INIFile class:

1public class Section : IEquatable<Section>
2{
3	public bool Equals(Section other)
4	{
5	    throw new NotImplementedException();
6	}
7}

We use IEquatable<Section> because we made a list of it.
public bool Equals(Section other) we need to add this because we used IEquatable<Section>, if called it will show the message NotImplementedException.
Let’s add some variables to this class:

1public string sectionName;
2public List<Key> keyList = new List<Key>();

sectionName this is the name of the section.
keyList this is a list of all the keys of the section.
We can now add a function to read a value of a key:

 1public string GetKeyValue(string key)
 2{
 3    string result = null;
 4    foreach(Key k in keyList)
 5    {
 6        if(k.keyName == key)
 7        {
 8            result = k.keyValue;
 9        }
10    }
11    return result;
12}

This will search for the key inside the list, if it find it, it will return its value, otherwise it will return null.
As we saw earlier we need also to set or add a key and its value, to do so we need to create a new function:

 1public void SetKeyValue(string key, string value)
 2{
 3    bool found = false;
 4    foreach (Key k in keyList)
 5    {
 6        if(k.keyName == key)
 7        {
 8            found = true;
 9            k.keyValue = value;
10        }                    
11    }
12    if(found == false)
13    {
14        keyList.Add(new Key() { keyName = key, keyValue = value });
15    }
16}

This function will search for the key, if it doesn’t exit it will add the new kay to the keyList, otherwise it will set the new value to the key.

Key Class

The last class that we need to make is the key class, this one is nested inside the section class, let’s define it:

1public class Key : IEquatable<Key>
2{
3	public bool Equals(Key other)
4    {
5        throw new NotImplementedException();
6    }
7}

IEquatable<Key> We created a list of keys, so just like the section class we need to add this.
public bool Equals(Key other) We need to add this because of IEquatable.
Inside this class we just need to add two variables, one will be the name of the key, the other will be the value:

1public string keyName;
2public string keyValue = "0";

I set the value of the key to “0” if its not specified.

Use the class

We now have created the class, so now we can test it.
I created a simple ini file called config.ini, I put it inside the working directory of our application.
Inside it I’ve wrote:

1[Section1]
2par1 = 123
3par2 = abc
4
5[Section2]
6par1 = 456
7par2 = def

Add a new button to our windows form, and double click it, then we can add some code to the Form:

1INIFile inf = new INIFile();

This will initialize our new class.
Inside the button click event add:

1inf.LoadINIFile("config.ini");
2MessageBox.Show(inf.GetSection("Section2").GetKeyValue("par2"));

inf.LoadINIFile will load the ini file.
MessageBox.Show this will show a message window.
inf.GetSection("Section2") .GetKeyValue("par2") this will give to us the value of the key par2 of the section Section2.
Calling this function, with the ini file that show to you earlier, will return the value def.
Responsive image

Remember, every value returned by the class will be a string.
As always you can see the full source code inside the next section.

Source Code

INIFIle.cs

  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Text;
  5using System.Threading.Tasks;
  6using System.IO;
  7
  8namespace INIProject
  9{
 10    class INIFile
 11    {
 12        public List<Section> sectionList = new List<Section>();
 13
 14        public void LoadINIFile(string fileName)
 15        {
 16            string curSection = null;
 17            string curKey = null;
 18            string curValue = null;
 19            foreach (string line in File.ReadLines(fileName))
 20            {
 21                if (line.StartsWith("["))
 22                {
 23                    curSection = line.Substring(1, line.Length - 2);
 24                    if (GetSection(curSection) == null)
 25                    {
 26                        sectionList.Add(new Section() { sectionName = curSection });
 27                    }
 28                }
 29                else if (line.Contains("="))
 30                {
 31                    curKey = line.Split(char.Parse("="))[0];
 32                    curValue = line.Split(char.Parse("="))[1];
 33                    GetSection(curSection).SetKeyValue(curKey.Trim(), curValue.Trim());
 34                }
 35            }
 36        }
 37
 38        public Section GetSection(string section)
 39        {
 40            Section result = null;
 41            foreach (Section s in sectionList)
 42            {
 43                if (s.sectionName == section)
 44                {
 45                    result = s;
 46                }
 47            }
 48            return result;
 49        }
 50
 51        public class Section : IEquatable<Section>
 52        {
 53            public string sectionName;
 54            public List<Key> keyList = new List<Key>();
 55
 56            public bool Equals(Section other)
 57            {
 58                throw new NotImplementedException();
 59            }
 60
 61            public string GetKeyValue(string key)
 62            {
 63                string result = null;
 64                foreach (Key k in keyList)
 65                {
 66                    if (k.keyName == key)
 67                    {
 68                        result = k.keyValue;
 69                    }
 70                }
 71                return result;
 72            }
 73            public void SetKeyValue(string key, string value)
 74            {
 75                bool found = false;
 76                foreach (Key k in keyList)
 77                {
 78                    if (k.keyName == key)
 79                    {
 80                        found = true;
 81                        k.keyValue = value;
 82                    }
 83                }
 84                if (found == false)
 85                {
 86                    keyList.Add(new Key() { keyName = key, keyValue = value });
 87                }
 88            }
 89
 90            public class Key : IEquatable<Key>
 91            {
 92                public string keyName;
 93                public string keyValue = "0";
 94                public bool Equals(Key other)
 95                {
 96                    throw new NotImplementedException();
 97                }
 98            }
 99
100        }
101    }
102}

Form1.cs

 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel;
 4using System.Data;
 5using System.Drawing;
 6using System.Linq;
 7using System.Text;
 8using System.Threading.Tasks;
 9using System.Windows.Forms;
10
11namespace INIProject
12{
13    public partial class Form1 : Form
14    {
15        INIFile inf = new INIFile();
16        public Form1()
17        {
18            InitializeComponent();
19        }
20
21        private void button1_Click(object sender, EventArgs e)
22        {
23            inf.LoadINIFile("config.ini");
24            MessageBox.Show(inf.GetSection("Section2").GetKeyValue("par2"));
25        }
26    }
27}

Form1.Designer.cs

 1namespace INIProject
 2{
 3    partial class Form1
 4    {
 5        private System.ComponentModel.IContainer components = null;
 6        protected override void Dispose(bool disposing)
 7        {
 8            if (disposing && (components != null))
 9            {
10                components.Dispose();
11            }
12            base.Dispose(disposing);
13        }
14
15        private void InitializeComponent()
16        {
17            this.button1 = new System.Windows.Forms.Button();
18            this.SuspendLayout();
19            // 
20            // button1
21            // 
22            this.button1.Location = new System.Drawing.Point(12, 12);
23            this.button1.Name = "button1";
24            this.button1.Size = new System.Drawing.Size(75, 23);
25            this.button1.TabIndex = 0;
26            this.button1.Text = "button1";
27            this.button1.UseVisualStyleBackColor = true;
28            this.button1.Click += new System.EventHandler(this.button1_Click);
29            // 
30            // Form1
31            // 
32            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
33            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
34            this.ClientSize = new System.Drawing.Size(800, 450);
35            this.Controls.Add(this.button1);
36            this.Name = "Form1";
37            this.Text = "Form1";
38            this.ResumeLayout(false);
39
40        }
41
42        private System.Windows.Forms.Button button1;
43    }
44}

Conclusion

Well done, now you can easly read data from a .ini file! 😄

Did you liked this tutorial?
Did you find it useful?
Let me know on Twitter! @CodeSailer