1,首先导入命名空间:
using System.Runtime.InteropServices;
2,声明API函数
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
3,创建ini文件
path = Application.StartupPath + "\\ClientCfg.ini";
private void WriteIni()
{
WritePrivateProfileString("DataBase", "DBSource", ".", path);
WritePrivateProfileString("DataBase", "DBPswd", "123456", path);
WritePrivateProfileString("DataBase", "DBAcc", "sa", path);
WritePrivateProfileString("DataBase", "DBName", "Train", path);
}
4,声明API函数
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
5,读取ini文件
private void ReadIni()
{
StringBuilder temp = new StringBuilder();
GetPrivateProfileString("DataBase", "DBSource", "", temp, 255, path);
string source = temp.ToString();
GetPrivateProfileString("DataBase", "DBPswd", "", temp, 255, path);
string pwd = temp.ToString();
GetPrivateProfileString("DataBase", "DBAcc", "", temp, 255, path);
string acc = temp.ToString();
GetPrivateProfileString("DataBase", "DBName", "", temp, 255, path);
string name = temp.ToString();
connectionStr = "server=" + source + ";database=" + name + ";uid=" + acc + ";pwd=" + pwd + "";
}