摘要:[C#][.Net] 呼叫Windows API 讀 寫 .INI 檔案
[筆記本]
記錄以前在VB時候常常呼叫API,現在改成使用 Visual Studio 2010撰寫時呼叫API方法有些小小改變,今日就將他記下來。
首先將開啟記事本撰寫所要讀取與寫入的值,在將記事本另存新檔副檔名為.ini。
引用必要條件
using System.Runtime.InteropServices;
設定必要API
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
Read .ini File
private void button2_Click(object sender, EventArgs e)
{
//Read ini File
OpenFileDialog Open = new OpenFileDialog();
Open.ShowDialog();
StringBuilder retVal = new StringBuilder(255); //回傳所要接收的值
string Section = "His name 2";
string Key = "Thread name 3";
string Defaut = "null"; //如果沒有 Section , Key 兩個參數值,則將此值賦給變量
int Size = 255; //設定回傳 Siez
int strref = GetPrivateProfileString(Section, Key, Defaut, retVal, Size, Open.FileName);
Console.WriteLine("Return Value {0}", retVal);
}
write .ini File
private void button1_Click(object sender, EventArgs e)
{ //Write ini File
OpenFileDialog Open = new OpenFileDialog();
Open.ShowDialog();
string Section = "His name 2";
string Key = "Thread name 3";
string Value = "Value 8888";
WritePrivateProfileString(Section, Key, Value, Open.FileName);
}