dotFusion.net

INI files manipulation using C#

Posted on: January 26th, 2009.
Category: C#

This time I’m going to present you the Windows way of Reading and Writing .INI files using C#.
 

This is far from the best way of doing this, because it works only when your executable is being run on Windows (this code uses kernel32.dll functions). Here is the base INI Read/Write class code:

 
Here’s the nuberings remover source:

using System;
using System.Runtime.InteropServices;
using System.Text;
 
namespace IniReadWrite
{
    class IniFile
    {
        [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,
          string key, string value, string iniFilePath);
        [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,
          string key, string defValue, StringBuilder retValue, int size, string iniFilePath);
 
        private const int valueLength = 255; // Maximum length of value
        private String iniPath; // The path of our .ini file
 
        public IniFile(String iniFilePath)
        {
            iniPath = iniFilePath;
        }
 
        public void WriteString(String section, String key, String value)
        {
            WritePrivateProfileString(section, key, value, iniPath);
        }
        public void WriteInt(String section, String key, int value)
        {
            WriteString(section, key, value.ToString());
        }
        public void WriteDouble(String section, String key, Double value)
        {
            WriteString(section, key, value.ToString());
        }
 
        public String ReadString(String section, String key, String defValue)
        {
            StringBuilder tmp = new StringBuilder(valueLength);
            int i = GetPrivateProfileString(section, key, defValue, tmp, valueLength, iniPath);
 
            return tmp.ToString();
        }
        public int ReadInt(String section, String key, int defValue)
        {
            return Int32.Parse(ReadString(section, key, defValue.ToString()));
        }
        public Double ReadDouble(String section, String key, Double defValue)
        {
            return Double.Parse(ReadString(section, key, defValue.ToString()));
        }
    }
}

 
Download this code and an example (Visual C# 2005 Express Edition Project)

I will soon be posting a version of this code that doesn’t need kernel32.dll and should work cross-platform even when compiled for Linux (using Mono).