using System.Runtime.InteropServices;
using System.Text;
public class IniFile
{
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileInt(string section, string key, int def, string filePath);
private readonly string _path;
public IniFile(string path) => _path = Path.GetFullPath(path);
// 寫入字串
public void Write(string section, string key, string value)
{
if (!WritePrivateProfileString(section, key, value, _path))
throw new IOException("寫入 INI 失敗");
}
// 讀取字串
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();
}
// 讀取整數
public int ReadInt(string section, string key, int defaultValue = 0)
=> GetPrivateProfileInt(section, key, defaultValue, _path);
// 刪除 Key
public void DeleteKey(string section, string key)
=> WritePrivateProfileString(section, key, null, _path);
// 刪除 Section
public void DeleteSection(string section)
=> WritePrivateProfileString(section, null, null, _path);
// 列舉所有 Section
public string[] GetSections()
{
// 需額外 API GetPrivateProfileSectionNames,略
return Array.Empty();
}
}
var ini = new IniFile(@"C:\App\config.ini");
// 寫入
ini.Write("Database", "Server", "192.168.1.100");
ini.Write("Database", "Port", "1433");
ini.Write("Settings", "AutoStart", "True");
// 讀取
string server = ini.Read("Database", "Server", "localhost");
int port = ini.ReadInt("Database", "Port", 1433);
bool auto = ini.Read("Settings", "AutoStart", "False") == "True";
Console.WriteLine($"{server}:{port} AutoStart={auto}");
Microsoft.Extensions.Configuration.Ini 純管理套件P/Invoke 封裝 kernel32.dll 是 C# 操作 INI 最輕量、相容性最好的方式。封裝為 IniFile 類別後,即可像操作字典一樣讀寫設定檔。