1、新建一个类;
- class IniClass
- {
- // 声明INI文件的写操作函数 WritePrivateProfileString()
- [System.Runtime.InteropServices.DllImport("kernel32")]
- private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
- // 声明INI文件的读操作函数 GetPrivateProfileString()
- [System.Runtime.InteropServices.DllImport("kernel32")]
- private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
- private string sPath = null;
- public void IniPath(string path)
- {
- this.sPath = path;
- }
- public void Writue(string section, string key, string value)
- {
- // section=配置节,key=键名,value=键值,path=路径
- WritePrivateProfileString(section, key, value, sPath);
- }
- public string ReadValue(string section, string key)
- {
- // 每次从ini中读取多少字节
- System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
- // section=配置节,key=键名,temp=上面,path=路径
- GetPrivateProfileString(section, key, "", temp, 255, sPath);
- return temp.ToString();
- }
- }
2、读取INI文件信息
- private void Readinfo()
- {
- string Current;
- Current = Directory.GetCurrentDirectory();//获取当前根目录
- IniClass ini = new IniClass();
- ini.IniPath(Current + "/mydata.ini");
- Autorun = ini.ReadValue("phpcms", "Autorun");
- timeinterval=ini.ReadValue("phpcms", "timeinterval");
- txt_Serverip.Text = ini.ReadValue("phpcms", "Server");
- DataBase = txt_database.Text = ini.ReadValue("phpcms", "DataBase");
- txt_user.Text = ini.ReadValue("phpcms", "Uid");
- txt_password.Text = ini.ReadValue("phpcms", "Pwd");
- }
3、将信息写入INI文件
- private void Saveinfo()
- {
- string Current;
- Current = Directory.GetCurrentDirectory();//获取当前根目录
- IniClass ini = new IniClass();
- ini.IniPath(Current + "/mydata.ini");
- Server = txt_Serverip.Text.Trim();
- DataBase = txt_database.Text.Trim();
- Uid = txt_user.Text.Trim();
- Pwd = txt_password.Text.Trim();
- ini.Writue("phpcms", "Server", Server);
- ini.Writue("phpcms", "DataBase", DataBase);
- ini.Writue("phpcms", "Uid", Uid);
- ini.Writue("phpcms", "Pwd", Pwd);
- }