How to read and write ini files using C#


The INI file format is an informal standard for configuration files for some platforms or software. INI files are simple text files with a basic structure composed of “sections” and “properties”. They are a deprecated standard on the Windows operating system. The use of the “INI file” has been changed in Windows in favor of the registry, and deprecated in .NET in favor of XML .config files. The name “INI file” comes from the filename extension usually used, “.INI”, that stands for “initialization”. If you are working with legacy applications you may require to read and manipulate ini files. Microsoft .Net framework doesn’t have API to manage ini files. But we can do it using WIN32 API calls. You can use WritePrivateProfileString() and GetPrivateProfileString() methods to write to ini file and read from ini file. Here I implemented a wrapper around these API functions, to read and write ini files.

public sealed class IniFile
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool WritePrivateProfileString
        (string section, string key, string value, string fileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    private static extern uint GetPrivateProfileString
        (string section, string key, string defaultValue,
        StringBuilder returnValue, uint size, string fileName);
    private string _fileName;

    public IniFile(string fileName)
        _fileName = fileName;

    public void Write(string section, string key, string value)
        WritePrivateProfileString(section, key, value, _fileName);

    public string Read(string section, string key)
        StringBuilder stringBuilder = new StringBuilder(255);
        GetPrivateProfileString(section, key, string.Empty,
            stringBuilder, 255, _fileName);
        return stringBuilder.ToString();

And you can use IniFile class like this

var ini = new IniFile(@"C:\Samples\Helloworld.ini");
ini.Write("General", "Show Splash screen", "true");

MessageBox.Show(ini.Read("General", "Show Splash screen"));

Happy Programming :)