Windows 提供三個核心 API 操作 INI 檔,均位於 kernel32.dll:
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
string lpAppName, // 區段名
string lpKeyName, // 鍵名
string lpString, // 值(null 代表刪除)
string lpFileName // INI 檔完整路徑
);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault, // 找不到時的預設值
StringBuilder lpReturnedString, // 接收緩衝區
int nSize, // 緩衝區大小
string lpFileName
);
[DllImport("kernel32")]
private static extern int GetPrivateProfileInt(
string lpAppName,
string lpKeyName,
int nDefault,
string lpFileName
);
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace EchonComponentLibrary
{
public class IniFile
{
private readonly string filePath;
[DllImport("kernel32", CharSet = CharSet.Auto)]
private static extern int GetPrivateProfileInt(
string lpAppName, string lpKeyName, int nDefault, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Auto)]
private static extern int GetPrivateProfileString(
string lpAppName, string lpKeyName, string lpDefault,
StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Auto)]
private static extern bool WritePrivateProfileString(
string lpAppName, string lpKeyName, string lpString, string lpFileName);
public IniFile(string fileName)
{
filePath = Path.GetFullPath(fileName);
}
public int ReadInt(string section, string key, int defaultValue)
{
return GetPrivateProfileInt(section, key, defaultValue, filePath);
}
public string ReadString(string section, string key, string defaultValue)
{
var sb = new StringBuilder(1024);
GetPrivateProfileString(section, key, defaultValue, sb, sb.Capacity, filePath);
return sb.ToString();
}
public void WriteInt(string section, string key, int value)
{
WritePrivateProfileString(section, key, value.ToString(), filePath);
}
public void WriteString(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, filePath);
}
public void DeleteKey(string section, string key)
{
WritePrivateProfileString(section, key, null, filePath);
}
public void DeleteSection(string section)
{
WritePrivateProfileString(section, null, null, filePath);
}
}
}
var ini = new IniFile(@"C:\Config\app.ini");
// 寫入
ini.WriteString("Database", "Server", "192.168.1.100");
ini.WriteInt("Database", "Port", 5432);
// 讀取
string server = ini.ReadString("Database", "Server", "localhost");
int port = ini.ReadInt("Database", "Port", 3306);
// 刪除
ini.DeleteKey("Database", "Port");
ini.DeleteSection("Database");
CharSet.Auto 會依平台自動選擇 Unicode/ANSI,現代 Windows 建議明確用 CharSet.Unicode。GetPrivateProfileString 的緩衝區需足夠大(例 1024),否則長字串會被截斷。appsettings.json,INI 適用於需與舊版軟體共存的場景。