Ini File Processing

// May 13th, 2010 // Useful Code

This is a class which will allow you to read old style .ini files. Sometimes you have an app which uses .ini and you need to read it in for whatever reason. Or perhaps you are looking to store your own apps settings in a .ini file because its what people are used to. In any event here is a sample .ini file this class will process.

Ini File


[Section 1]
Test = 1
Test2 = 1

[Section 2]
blah = foo
foo = blah

[Section 3]
var = more settings
test = this will handle = signs as part of the value also

Sample Code


            IniFileReaderLib.IniFile tmpIni = new IniFileReaderLib.IniFile("Settings.ini");
            Console.WriteLine(tmpIni.Section["Section 1"]["test"]);

Code


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;

namespace IniFileReaderLib
{
    /// <summary>
    /// PROVIDES ROUTINES FOR READING AND PROCESSING A .INI FILE
    /// </summary>
    public class IniFile
    {
        /// <summary>
        /// HOLDS ALL THE VARIABLES LISTED IN THE INI FILE BASED ON obj["Section"]["Setting"]
        /// </summary>
        public Dictionary<string, Dictionary<string, string>> Section { get; set; }

        /// <summary>
        /// DID THE FILE CONTAIN ERRORS WHEN ATTEMPTING TO LOAD
        /// </summary>
        public bool HasErrors { get; set; }

        /// <summary>
        /// WHAT WERE THE ERRORS CONTAINED IN THE FILE
        /// </summary>
        public List<string> Errors { get; set; }

        /// <summary>
        /// FILENAME OF THE INI FILE WE ARE PROCESSING
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// CLASS INITIALIZER
        /// </summary>
        /// <param name="FileName">FILENAME TO PROCESS</param>
        public IniFile(string FileName)
        {
            //STORE THE NAME OF THE FILE WE ARE TO PROCESS
            this.FileName = FileName;

            //PROCESS THE FILE
            ReloadFile();
        }

        /// <summary>
        /// RELOAD THE INI FILE INCASE IT HAS CHANGED SINCE THIS CLASS WAS CREATED
        /// </summary>
        /// <param name="FileName">FILENAME OF THE INIFILE TO PROCESS</param>
        public void ReloadFile()
        {
            //CLEAR OUT ALL THE VALUES BY RELEASING THE OBJECT
            Section = new Dictionary<string, Dictionary<string, string>>(StringComparer.CurrentCultureIgnoreCase);
            Errors = new List<string>();

            //CREATE A TEXT READER TO READ THE INI FILE
            using (TextReader tmpReader = (TextReader)File.OpenText(FileName))
            {
                string tmpLine = null;
                string curSection = null;

                //LOOP THROUGH THE ENTIRE FILE ADDING VARIABLES TO THE SECTION
                while ((tmpLine = tmpReader.ReadLine()) != null)
                {
                    //IF THE LINE IS A SECTION THEN ADD IT TO THE SECTIONS AND START ADDING VARIABLES TO THE SECTION
                    if (Regex.Match(tmpLine, @"[[].*[]]").Success)
                    {
                        //PARSE THE SECTION OUT OF THE STRING AND APPEND IT TO THE LIST OF SECTIONS
                        curSection = Regex.Match(tmpLine, @"[[](?<Section>.*)[]]").Groups["Section"].Value;
                        Section[curSection] = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
                    }
                    else
                    {
                        try
                        {
                            //IF THERE IS DATA ON THE LINE THEN TRY TO PROCESS IT
                            if (!string.IsNullOrEmpty(tmpLine) && tmpLine.Contains("="))
                            {
                                //SPLIT THE STRING UP SO WE CAN GET THE VAR TO THE LEFT OF THE = SIGN
                                string[] curPair = tmpLine.Split('=');

                                //ADD THE ITEM TO THE COLLECTION AND MAKE SURE TO PIECE ANYTHING BACK TOGETHER ON THE RIGHT OF THE FIRST = SIGN
                                Section[curSection].Add(curPair[0].Trim(), string.Join("=", curPair.Skip(1).ToArray()).Trim());
                            }
                        }
                        catch(Exception e)
                        {
                            //TRACK THAT AN ERROR WAS THROWN
                            HasErrors = true;

                            //ADD THE MESSAGE TO THE ERROR LIST
                            Errors.Add(e.Message);
                        }
                    }
                }
            }
        }
    }
}
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • Google Reader
  • DeviantArt