public class IniFile
{
[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);
public string GetFileName
{
get;
set;
}
public IniFile(string filePath)
{
GetFileName = filePath;
}
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section"></param>
/// <param name="key">键</param>
/// <param name="value">值</param>
public void WriteValue(string Section, string key, string value)
{
WritePrivateProfileString(Section, key, value, GetFileName);
}
/// <summary>
/// 读取INI文件
/// </summary>
/// <param name="Section"></param>
/// <param name="key">待获取数据的键</param>
/// <param name="defValue">表示当通过键获取数据时,如果键不存在或无法找到数据,则返回该值</param>
/// <returns></returns>
public string ReadValue(string Section, string key, string defValue)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, key, defValue, temp, 255, this.GetFileName);
return temp.ToString();
}
}
应用:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
IniFile ini = new IniFile("C:\\config.ini");
private void button1_Click(object sender, EventArgs e)
{
ini.WriteValue("Config", "Port", "COM1");
}
private void button2_Click(object sender, EventArgs e)
{
string port = ini.ReadValue("Config", "Port", "COM2");
}
}
结果:
写入:
[Config]
Port=COM1
读出:
COM1,
假如我改成这样: string port = ini.ReadValue("Config", "Port123", "COM2");,该Port123键不存在INI文件中,那么port的值就为COM2