INI 文件雖老舊,但在輕量級配置、跨進程共享、無註冊表權限場景仍廣泛使用。C# 通過 P/Invoke 調用 Windows API GetPrivateProfileString、WritePrivateProfileString 可高效操作 INI。本文提供生產級封裝類完整代碼。
using System.Runtime.InteropServices;
using System.Text;
public class IniFile {
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetPrivateProfileString(
string lpAppName, string lpKeyName, string lpDefault,
StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int WritePrivateProfileString(
string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetPrivateProfileSection(
string lpAppName, IntPtr lpReturnedString, int nSize, string lpFileName);
private readonly string _path;
public IniFile(string path) { _path = Path.GetFullPath(path); }
}
// 讀取值(支持默認值)
public string Read(string section, string key, string defaultValue = "") {
var sb = new StringBuilder(256);
GetPrivateProfileString(section, key, defaultValue, sb, sb.Capacity, _path);
return sb.ToString();
}
// 寫入值(section/key 為 null 可刪除整節/鍵)
public void Write(string section, string key, string value) {
if (value == null) value = ""; // 空字符串表示刪除鍵
WritePrivateProfileString(section, key, value, _path);
}
// 刪除鍵
public void DeleteKey(string section, string key) {
WritePrivateProfileString(section, key, null, _path);
}
// 刪除整節
public void DeleteSection(string section) {
WritePrivateProfileString(section, null, null, _path);
}
// 讀取整節所有鍵值
public Dictionary<string, string> ReadSection(string section) {
var dict = new Dictionary<string, string>();
IntPtr ptr = Marshal.AllocHGlobal(65536);
try {
int size = GetPrivateProfileSection(section, ptr, 65536, _path);
if (size > 0) {
string data = Marshal.PtrToStringAuto(ptr, size);
foreach (var pair in data.Split('\0', StringSplitOptions.RemoveEmptyEntries)) {
int idx = pair.IndexOf('=');
if (idx > 0) dict[pair.Substring(0, idx)] = pair.Substring(idx + 1);
}
}
} finally { Marshal.FreeHGlobal(ptr); }
return dict;
}
public partial class MainForm : Form {
private readonly IniFile _ini = new IniFile(Application.StartupPath + @"\config.ini");
private void btnWrite_Click(object sender, EventArgs e) {
_ini.Write("Settings", "Username", txtUser.Text);
_ini.Write("Settings", "Theme", cmbTheme.SelectedItem?.ToString() ?? "Light");
MessageBox.Show("寫入成功");
}
private void btnRead_Click(object sender, EventArgs e) {
txtUser.Text = _ini.Read("Settings", "Username", "Guest");
cmbTheme.SelectedItem = _ini.Read("Settings", "Theme", "Light");
}
private void btnDeleteKey_Click(object sender, EventArgs e) {
_ini.DeleteKey("Settings", "Username");
}
private void btnDeleteSection_Click(object sender, EventArgs e) {
_ini.DeleteSection("Settings");
}
}
; config.ini
[Settings]
Username=Admin
Theme=Dark
GetPrivateProfileStringW/WritePrivateProfileStringW 並將 CharSet = CharSet.Unicode。Microsoft.Extensions.Configuration.Ini(NuGet 包),無需 P/Invoke,跨平台。封裝 Windows API 操作 INI 文件僅需十幾行核心代碼,配合 StringBuilder、Marshal 處理非托管內存,即可獲得穩定、高性能的配置讀寫能力。