logo

CSharp IniReader

Description

This code snippet is a class designed to process an INI file in the form of keypairs. An example of the content of such an INI file is as followed:

var = This is a string variable, note that there are no quotes.
var2 = 2

; Some comment
[Some Section]
var3 = true

Members

Public IniReader(string) - Constructor

Constructor for this class. This will read the file that is given, and parse it. This method may throw exceptions, so use a try-catch block to handle any thrown exceptions.

IniReader ir;

try
{
    ir = new IniReader("myfile.ini");
}
catch(Exception e)
{
    // Handle exceptions
}

string variable = ir.GetIniVar("variable");

Public string GetIniVar(string, string, string)

This function retrieves a variable from the INI-file. If the variable is not found, the function will return the given default value. For every primitive type, there is a similar function that does the same, these functions are:

bool GetIniVarBool(string variable_name, bool default_value);
byte GetIniVarByte(string variable_name, byte default_value);
float GetIniVarFloat(string variable_name, float default_value);
double GetIniVarDouble(string variable_name, double default_value);
short GetIniVarShort(string variable_name, short default_value);
int GetIniVarInteger(string variable_name, int default_value);
long GetIniVarLong(string variable_name, long default_value);

You can of course extend or modify this for your own purpose.

Source Code

/* *****  Copyright (c) 2002-2014, Steve Mathot & Co, All rights reserved. *****
* **
* **  Purpose:     This class will process INI Files with keypair definitions.
* **  Reference:   http://mcodev.stevemathot.com
* **  Keywords:    $
* **  Author:      Steve Mathot http://www.stevemathot.com/contact
* **  Last Edited: 28 June 2013
* **  License:     MIT License
* **
* ***************************************************************************** */

using System;
using System.IO;
using System.Collections.Generic;


namespace mCoDev
{
    /// <summary>
    /// Reads an ini file that is built up in key-value format.
    /// </summary>
    public class IniReader
    {

        Dictionary<string, string> dict = new Dictionary<string, string>();


        /// <summary>
        /// Creates a new instance of the IniReader class. May throw exception!
        /// </summary>
        /// <param name="filename">Location of the ini file to read.</param>
        public IniReader(string filename)
        {
            string[] file = System.IO.File.ReadAllLines(filename);

            foreach (string line in file)
            {
                if (line.Trim() != "")
                {
                    if (line.Trim().Substring(0, 1) != ";" && line.Trim().Substring(0, 1) != "[")
                    {
                        if (line.IndexOf('=') > 0)
                        {
                            string[] p = line.Split('=');
                            dict.Add(p[0].Trim(), p[1].Trim());
                        }
                    }
                }
            }
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public string GetIniVar(string key, string defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;
                    return entry.Value;
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public bool GetIniVarBool(string key, bool defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    return (entry.Value == "1" || entry.Value.ToLower() == "true");
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public byte GetIniVarByte(string key, byte defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return byte.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public float GetIniVarFloat(string key, float defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return float.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public double GetIniVarDouble(string key, double defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return double.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public short GetIniVarShort(string key, short defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return short.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public int GetIniVarInt(string key, int defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return int.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }



        /// <summary>
        /// Gets a dictionary entry from the ini file.
        /// </summary>
        /// <param name="key">Variable key to get the value from.</param>
        /// <param name="defaultValue">The default value to return if the key is not found.</param>
        public long GetIniVarLong(string key, long defaultValue)
        {
            foreach (KeyValuePair<string, string> entry in dict)
            {
                if (entry.Key == key)
                {
                    if (entry.Value.ToLower() == "default") return defaultValue;

                    try
                    {
                        return long.Parse(entry.Value);
                    }
                    catch
                    {
                        return defaultValue;
                    }
                }
            }

            return defaultValue;
        }

    }
}

See Also