解决问题时候,发现ini文件相对于txt文件的优点,所以找资料学习了ini文件的存储操作
首先是ini文件的格式:
例:
[张三]
名称=zs
性别=男
[设置]
颜色=red
模式=1
类型=3
INI文件由节、键、值组成
[section1]
key1=value1
key2=value2
[section2]
key1=value1
key2=value2
key3=value3
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//using System.Runtime.InteropServices;//若此命名空间不注释掉,下面的[System.Runtime.InteropServices.DllImport("kernel32")]改为[DllImport("kernel32")]
在类中申明ini文件的读取api函数
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern long WritePrivateProfileString(
string lpAppName, // pointer to section name
string lpKeyName, // pointer to key name
string lpString, // pointer to string to add
string lpFileName // pointer to initialization filename
);
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int GetPrivateProfileString(
string lpAppName, // points to section name
string lpKeyName,// points to key name
string lpDefault,// points to default string
StringBuilder lpReturnedString,// points to destination buffer
int nSize, // size of destination buffer
string lpFileName// points to initialization filename
);
对按钮事件的响应
写入
private void button2_Click(object sender, EventArgs e)
{
long l = WritePrivateProfileString("2013.9.11", "input", "ccc", System.Environment.CurrentDirectory + @"/a.ini");
MessageBox.Show(l.ToString());
// WritePrivateProfileString("2000",null,null,System.Environment.CurrentDirectory + @"/b.ini");
WritePrivateProfileString("2000", "ddd", "ccc", System.Environment.CurrentDirectory + @"/d.ini");
WritePrivateProfileString("3000", "input", "1646494916316", System.Environment.CurrentDirectory + @"/a.ini");
WritePrivateProfileString("300000", "inputddafd", "ccasdfasfc", System.Environment.CurrentDirectory + @"/a.ini");
WritePrivateProfileString("",null,null, System.Environment.CurrentDirectory + @"/f.ini");
WritePrivateProfileString("", "", "", System.Environment.CurrentDirectory + @"/e.ini");
}
读取
private void button1_Click(object sender, EventArgs e)
{
StringBuilder temp = new StringBuilder(255);
GetPrivateProfileString(@"2013.9.12", @"complement", @"error", temp, 255, System.Environment.CurrentDirectory + @"/a.ini");
MessageBox.Show(temp.ToString());
}
参考:
MSDN Library
Visual Studio 6.0
http://www.cnblogs.com/tianxiao/archive/2008/05/28/1209300.html
http://www.cnblogs.com/gaohades/archive/2006/01/24/322751.html