C# – Working with INI files

Long time ago developers used INI files to store application data. The INI file format is a common format for configuration files. INI files are simple text files with a basic structure. They are commonly associated with Microsoft Windows, but are also used on other platforms. The use of the “INI file” has been deprecated in Windows and corresponding data should be placed in the registry. The name “INI file” comes from the filename extension usually used, “.INI”, that stands for “initialization”. Sometimes files using the INI file format will use a different extension, such as “.CFG”, “.conf”, or “.TXT”. For more details about INI files you can read at following link http://en.wikipedia.org/wiki/INI_file . To work with this format, many developers tried to build a class for reading and writing value from specific section. They combined dictionary type and regular expressions to build a cross-platform INI helper class. That means their classes don’t use any API of any specific operating system.
However if we define that our applications only run under Windows, then I would like to share a wrapper which wraps two APIs used for reading and writing with INI files. They are GetPrivateProfileString and WritePrivateProfileString. Because they are APIs so we must declare their signature so that we can use with c#

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        static extern uint GetPrivateProfileString(
           string lpAppName,
           string lpKeyName,
           string lpDefault,
           StringBuilder lpReturnedString,
           uint nSize,
           string lpFileName);

        [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool WritePrivateProfileString(string lpAppName,
           string lpKeyName, string lpString, string lpFileName);

My wrapper will wrap these APIs in 2 normal function of IniWorker class. This class needs the path to INI files as its arguments

public IniWorker(string strIniPath,bool bCreateFileIfNotExists)
{
	m_strIniPath = strIniPath;
	if (!CheckFileExists() && bCreateFileIfNotExists)
	{
		File.Create(strIniPath);
	}
}

To read value of a key in an application name use simple code below

IniWorker iwWorker = new IniWorker("e:\\Sample.ini",true);
Console.WriteLine(iwWorker.IniReadValue("database", "server"));
Console.ReadLine();

It’s very simple but I would like to share because I see a lot of developers wrote complex code to work with this format. You can download my wrapper at this link “IniWorker