ini文件格式
[Section1] KeyWord1 = Valuel KeyWord2 = Value2 …… [Section2] KeyWord3 = Value3 KeyWord4 = Value4
代码段
[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); /*参数:section:INI文件中的段落;key:INI文件中的关键字; val:INI文件中关键字的数值;filePath:INI文件的路径。*/ private void buttonRead_Click(object sender, EventArgs e) { /*正确读取INI的必须满足三个前提:INI文件的全路径、段落名称和关键字名称。 否则就无法正确读取。你可以设定读取不成功后的缺省数值, 在下面的程序中,为了直观设定的是“无法读取对应数值!”字符串。*/ StringBuilder temp = new StringBuilder(255); // int i = GetPrivateProfileString("段落名称一", "键一", "无法读取对应数值!",temp,255, SettingsPath); int i = GetPrivateProfileString("Data", "User", "无法读取对应数值!", temp, 255, SettingsPath); int jj = temp.Length; MessageBox.Show("键一=" + temp.ToString()); } private void buttonWrite_Click(object sender, EventArgs e) { /*对INI文件进行写操作的时候,如果此时在INI文件中存在和 要写入的信息相同的段落名称和关键字,则将覆盖此INI信息。*/ //WritePrivateProfileString("段落名称一", "键一", "值一", SettingsPath); WritePrivateProfileString("Data", "User", "张三", SettingsPath); WritePrivateProfileString("段落名称三", "键三", "值三", SettingsPath); MessageBox.Show("成功写入INI文件!", "信息"); } string SettingsPath = @"./\\Settings.ini"; private void buttonModify_Click(object sender, EventArgs e) { //删除一个键值 WritePrivateProfileString("段落名称一", "键一", null, SettingsPath); //删除一个段落 WritePrivateProfileString("段落名称一", null, null, SettingsPath); }