SoFunction
Updated on 2025-03-01

C# implements reading and writing ini file class instances

This article describes the C# implementation of reading and writing ini file classes. Share it for your reference. The details are as follows:

This C# class encapsulates various functions required to operate on INI configuration files, including reading key values, reading key values, deleting paragraphs, etc.

using System;
using ;
using ;
namespace 
{
  /// <summary>
  /// INI file read and write class.  /// </summary>
  public class INIFile
  {
    public string path;
    public INIFile(string INIPath)
    {
      path = INIPath;
    }
    [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);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
    /// <summary>
    /// Write INI files    /// </summary>
    /// <param name="Section"></param>
    /// <param name="Key"></param>
    /// <param name="Value"></param>
    public void IniWriteValue(string Section,string Key,string Value)
    {
      WritePrivateProfileString(Section,Key,Value,);
    }
    /// <summary>
    /// Read the INI file    /// </summary>
    /// <param name="Section"></param>
    /// <param name="Key"></param>
    /// <returns></returns>
    public string IniReadValue(string Section,string Key)
    {
      StringBuilder temp = new StringBuilder(255);
      int i = GetPrivateProfileString(Section,Key,"",temp, 255, );
      return ();
    }
    public byte[] IniReadValues(string section, string key)
    {
      byte[] temp = new byte[255];
      int i = GetPrivateProfileString(section, key, "", temp, 255, );
      return temp;
    }
    /// <summary>
    /// Delete all paragraphs under the ini file    /// </summary>
    public void ClearAllSection()
    {
      IniWriteValue(null,null,null);
    }
    /// <summary>
    /// Delete all keys under the personal paragraph under the ini file    /// </summary>
    /// <param name="Section"></param>
    public void ClearSection(string Section)
    {
      IniWriteValue(Section,null,null);
    }
  }
}

I hope this article will be helpful to everyone's C# programming.