Monday, 17 February 2014

Read and Write ini file in c#

Description:

In this article, I am going write C# code example to Read Ini file and Write Ini file using Native Windows API functions ReadPrivateProfileString and WritePrivateProfileString.

Summary:


Ini File structure

  - An INI file consists of various sections, each of one defines various unique keys with an unique value assigned to each key.
  - Sections are declared as a unique word enclosed in square brackets. Spaces enclosed into the square brackets are ignored, but the section must be defined with an unique word.
  - Inside a section, Keys must be unique within the same section, but can have the same key name in different sections. A key is assigned using the equal sign (key = value) .

Sample Ini file:
[Install]
Mode="Advanced"
Port=8080
Path=C:\Program Files\Setup

Read INI file in C# using ReadPrivateProfileString API function

To Read INI file setting in C#, we need to add ReadPrivateProfileString Window API function.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern uint GetPrivateProfileString(
        string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
        uint nSize, string lpFileName);

    static void Main(string[] args)
    {
        string value = ReadINISetting(@"C:\Users\Administrator\Desktop\Setup.ini", 
                                         "Install", "Mode");
        Console.WriteLine(value);
    }
    
    static string ReadINISetting(string iniFilePath, string section, string key)
    {
        var retVal = new StringBuilder(255);

        GetPrivateProfileString(section, key, "", retVal, 255, iniFilePath);

        return retVal.ToString();
    }

Write INI file in C# using WritePrivateProfileString API function

To Write Ini file setting in C#, we need to add WritePrivateProfileString Window API function.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern bool WritePrivateProfileString(
        string lpAppName, string lpKeyName, string lpString, string lpFileName);

    static void Main(string[] args)
    {
        WriteINISetting(@"C:\Users\Administrator\Desktop\Setup.ini", "Install",
                             "Path", @"C:\Program Files\Setup");
    }

        
    static void WriteINISetting(string iniFilePath, string section, string key,string value)
    {
        WritePrivateProfileString(section, key, value, iniFilePath);
    }

Thanks,
Morgan
Software Developer

Advertisements
Advertisements

1 comment:

  1. - Sections are declared as a unique word enclosed in square brackets. Spaces enclosed into the square brackets are ignored, but the section must be defined with an unique word.file upload

    ReplyDelete