1、首先导入命名空间:using System.Runtime.InteropServices;//引用DllImport
using System.Text;//引用StringBuilder
2、声明API函数
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
3、创建ini文件
WritePrivateProfileString("MyAccount", "ID", "30643300", @"D:\Account.ini");
WritePrivateProfileString("MyAccount", "PWD", "**********", @"D:\Account.ini");
4、声明API函数
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
5、读取ini文件
StringBuilder temp = new StringBuilder();
GetPrivateProfileString("MyAccount", "ID", "账号错误", temp, 255, @"D:\Account.ini");
string ID = temp.ToString();
GetPrivateProfileString("MyAccount", "PWD", "读取出错", temp, 255, @"D:\Account.ini");
string PWD = temp.ToString();
MessageBox.Show(ID + ":" + PWD);