Access INI File with C#

Hi have a good day

This simple class will allow to Write and Read INI Files ( Old Windows Settings Files )

using System;
using System.Runtime.InteropServices;
using System.Text;

class INIFile
{
    [DllImport("kernel32.dll")]
    private static extern int WritePrivateProfileString(string ApplicationName, string KeyName, string StrValue, string FileName);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileString(string ApplicationName, string KeyName, string DefaultValue, StringBuilder ReturnString, int nSize, string FileName);
    

    public static void WriteValue(string SectionName , string KeyName, string KeyValue, string FileName)
    {
        WritePrivateProfileString(SectionName , KeyName, KeyValue, FileName);
    }

    public static string ReadValue(string SectionName , string KeyName , string FileName)
    {
        StringBuilder szStr = new StringBuilder(255);
        GetPrivateProfileString(SectionName, KeyName, "" , szStr, 255, FileName);
        return szStr.ToString().Trim();
    }
}

How to Use :

using System;

class Program
{
    static void Main(string[] args)
    {
        INIFile.WriteValue("Sample Section", "Some Key", "SomeValue", "c:\\test.ini");

        string value = INIFile.ReadValue("Sample Section", "Some Key", "c:\\test.ini");

        Console.WriteLine(value);
    }
}

Hope you will find use of it.

Comments

    1. I am fully respect the copyright of all the information in the public domain.
      And I would be very happy, if you provide me with a prove of your claim.

  1. This Win API solution for INI files is very popular on the net. However it is said to be provided for backward compatibility with old 16-bit Windows applications, so it might disappear in future Windows OS.
    Additionally, it seems crippled to only 254 byte values for keys. I have hard time now to make it work with larger texts so I have to write my own class to handle INI files.

  2. Hi, I think your site might be having browser compatibility issues.
    When I look at your blog in Safari, it looks fine but when opening in
    Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, awesome blog!

  3. Pingback: cheap wow gold

Leave a Reply

Your email address will not be published.