透過 Windows API 實現 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 完整路徑、區段名稱、鍵值名稱。若讀取失敗可指定預設值。
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 函數。[Section] 區段 → Key=Value 鍵值對。