INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下
[Section1]
key 1 = value2
key 1 = value2
……
[Section2]
key 1 = value1
key 2 = value2
文件由若干个段落(section)组成,每个段落又分成若干个键(key)和值(value)。Windows系统自带的Win32的API函数GetPrivateProfileString()和WritePrivateProfileString()分别实现了对INI文件的读写操作,他们位于kernel32.dll下。
但是令人遗憾的是C#并没有提供相关INI文件操作的函数,所以唯一比较理想的方法就是调用API函数。
接下来我就简单讲解下函数GetPrivateProfileString()和WritePrivateProfileString()的参数讲解
读取操作:
[DllImport("kernel32")]







写入操作:
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
section: 要写入的段落名
key: 要写入的键,如果该key存在则覆盖写入
val: key所对应的值
filePath: INI文件的完整路径和文件名
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public class INIFile
{
public string 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);
public INIFile(string INIPath)
{
inipath = INIPath;
}
public void IniWriteValue(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, inipath);
}
public string IniReadValue(string section, string key)
{
StringBuilder temp = new StringBuilder(500);
int length = GetPrivateProfileString(section, key, "", temp, 500, inipath);
return temp.ToString();
}
}