Read INI Files

Introduction

LINQ (Language Integrated Query) is a programmatic tool to manipulate data. It can work on lists or dictionaries in memory (IEnumerable) or with databases (IQueryable). You can easily improve the performance of the application using Parallel Linq. I would like to demonstrate how to simplify the reading of the INI files. We will put data from the INI file into a dictionary.

Solution

Suppose your INI file looks like below,

Value1=Test1
Value2=Test2
Value3=Test1=Test2

Char "=" can exist in value.

We would like to get a generic Dictionary<string, string>. If the duplicate key exists in our INI file, we will get an exception. 

First, we need to read the INI file. I will use File.ReadLines, because I do not wish to load the whole file into the memory.

Next, in Linq Select, I use a string.Split function to split into a string array with “=” parameter.

We extract the first element of the array as our key. Now we need to generate a value.

We use an indexed Linq Select syntax to extract all elements. The indexed version of Linq select gives us a unique opportunity to have an index element of an array, and an element. We use Linq Where to remove the first element (number 0). We use string. Join function with “=” to join an enumerable list into a value of our dictionary.

Finally, we use ToDictonary to materialize our generic dictionary.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqIniFile {
    class Program {
        static Dictionary < string, string > ReadIniFile(string fileName) {
            return File.ReadLines(fileName).Select(s => s.Split('=')).Select(s => new {
                key = s[0], value = string.Join("=", s.Select((o, n) => new {
                    n,
                    o
                }).Where(o => o.n > 0).Select(o => o.o))
            }).ToDictionary(o => o.key, o => o.value);
        }
        static void Main(string[] args) {
            foreach(var item in ReadIniFile("test.ini")) {
                Console.WriteLine(string.Format("{0}, {1}", item.Key, item.Value));
            }
        }
    }
}

Summary

We can see that implementing the reading of the INI files is not that complicated, but just the opposite. As you can see, Linq is a very powerful tool for C# programmers.