Read Write ini file : ini file « Development Class « C# / C Sharp






Read Write ini file

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

class MainClass {
    [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString")]
    private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
    [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString")]
    private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

    static void Main(string[] args) {
        string val;
        val = GetIniValue("A", "Key1", "\\initest.ini");
        Console.WriteLine(val);
        WriteIniValue("B", "Key1", "New Value", "\\initest.ini");

        val = GetIniValue("C", "Key1", "\\initest.ini");
        Console.WriteLine(val);

        WriteIniValue("D", "Key1", "Value1", "\\initest.ini");
    }

    public static string GetIniValue(string section, string key, string filename) {
        int chars = 256;
        StringBuilder buffer = new StringBuilder(chars);
        string sDefault = "";
        if (GetPrivateProfileString(section, key, sDefault,
          buffer, chars, filename) != 0) {
            return buffer.ToString();
        } else {
            return null;
        }
    }

    public static bool WriteIniValue(string section, string key, string value, string filename) {
        return WritePrivateProfileString(section, key, value, filename);
    }
}

 








Related examples in the same category