Example of a method in C that reads and writes INI files
- 2020-05-10 18:42:06
- OfStack
Usually C# USES an XML-based configuration file, but you may still need to use the INI file if you need to, for example, accommodate older systems.
However, C# does not have API itself to read and write INI files, and it does so only by calling unmanaged code, the system's own API.
The corresponding read-write methods are GetPrivateProfileString and WritePrivateProfileString, respectively.
Parameters in GetPrivateProfileString:
lpAppName -- name of section
lpKeyName -- name of key
lpDefault -- copy this value to lpReturnedString if lpKeyName is not found
lpReturnedString -- the value used to return the result
nSize -- the character length of lpReturnedString
lpFileName -- INI file name
Parameters in WritePrivateProfileString:
lpAppName -- name of section
lpKeyName -- name of key
lpString -- the value corresponding to lpKeyName
lpFileName -- INI file name
The actual code is as follows:
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace INIDemo
{
class Program
{
static void Main(string[] args)
{
WritePrivateProfileString("Demo", "abc", "123", "c:\\demo.ini");
StringBuilder temp = new StringBuilder();
GetPrivateProfileString("Demo", "abc", "", temp, 255, "c:\\demo.ini");
Console.WriteLine(temp);
Console.ReadLine();
}
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool WritePrivateProfileString(
string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetPrivateProfileString(
string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
int nSize, string lpFileName);
}
}
The contents of INI file after the program is run are as follows:
[Demo]
abc=123
This is a relatively simple approach, and if you don't want to use unmanaged methods, you can take a more cumbersome approach to the problem.
Because the format of the INI file is fixed, you can do the same thing by writing a corresponding parser, just the usual string manipulation.
If you don't want to do it yourself, don't worry, there's a program out there, Cinchoo framework, to do what you want to do.
And then the one cut becomes easy again.