SamKr
11/19/2014 - 3:42 PM

Read and write ini files

Read and write ini files

using System.Runtime.InteropServices;

class clsINIFile
{
    private string _filePath;

    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
        string key,
        string val,
        string filePath);

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
        string key,
        string def,
        StringBuilder retVal,
        int size,
        string filePath);

    public Ini(string filePath)
    {
        _filePath = filePath;
    }

    public void Write(string section, string key, string value)
    {
        try
        {
            WritePrivateProfileString(section, key, value, _filePath);
        }
        catch
        {
        }
    }

    public string Read(string section, string key)
    {
        try
        {
            var sb = new StringBuilder(255);
            GetPrivateProfileString(section, key, "", sb, 255, _filePath);
            return sb.ToString();
        }
        catch
        {
            return null;
        }
    }

    public string FilePath
    {
        get { return _filePath; }
        set { _filePath = value; }
    }
}