首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 操作 INI 檔案簡易教學:讀寫 API 封裝與實戰範例

     編輯:關於C語言

核心 API:WritePrivateProfileString / GetPrivateProfileString

透過 Windows API 實現 INI 檔案讀寫。寫入時若區段與鍵值已存在則覆蓋。

寫入 INI 範例

private void button2_Click(object sender, System.EventArgs e) {
    string fileName = textBox1.Text;
    string section = textBox2.Text;
    string key = textBox3.Text;
    string keyValue = textBox4.Text;
    WritePrivateProfileString(section, key, keyValue, fileName);
    MessageBox.Show("成功寫入 INI 檔案!", "資訊");
}

讀取 INI 範例

讀取需三要素:INI 完整路徑、區段名稱、鍵值名稱。若讀取失敗可指定預設值。

private void button3_Click(object sender, System.EventArgs e) {
    StringBuilder temp = new StringBuilder(255);
    string fileName = textBox1.Text;
    string section = textBox2.Text;
    string key = textBox3.Text;
    int i = GetPrivateProfileString(section, key, "無法讀取對應數值!", temp, 255, fileName);
    textBox4.Text = temp.ToString();
}

注意事項

  • 需引用 System.Runtime.InteropServices 並以 DllImport("kernel32.dll") 匯入兩個 API 函數。
  • INI 結構:[Section] 區段 → Key=Value 鍵值對。
  • 適用於簡單設定儲存,複雜資料建議改用 XML 或 JSON。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved