首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 讀寫 INI 檔案:P/Invoke 封裝 Kernel32 API 完整實作

     編輯:C# 入門

核心 API 宣告


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}");

注意事項

  • CharSet.Unicode:支援中文路徑與內容
  • StringBuilder 容量:預設 256,超長值需加大
  • 檔案不存在:API 會自動建立,目錄需存在
  • 效能:頻繁讀寫會反覆開關檔案,大量操作建議快取在記憶體、統一寫入
  • 替代方案:.NET Core / 5+ 建議用 Microsoft.Extensions.Configuration.Ini 純管理套件

結語

P/Invoke 封裝 kernel32.dll 是 C# 操作 INI 最輕量、相容性最好的方式。封裝為 IniFile 類別後,即可像操作字典一樣讀寫設定檔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved