C# ini文件读写实例
ini文件一般用于保存当前运行的程序或者一些临时的配置属性的文件。也有时用于保存一定的数据以便于临时或者配置上的需要。
文本格式如下:
[Section1 Name] ---------用 []括起来,其包含多个key KeyName1=value1 ------格式是 Key=value。 KeyName2=value2 ... [Section2 Name] KeyName1=value1 KeyName2=value2
其中有专门读写ini文件的windows方法:
[DllImport("kernel32")]
// 写入ini文件操作section,key,value
private static extern long WritePrivateProfileString(string section,string key, string val, string filePath);
[DllImport("kernel32")]
// 读取ini文件操作section,key,和返回的keyvalue
private static extern int GetPrivateProfileString(string section,string key, string def, StringBuilder retVal,int size, string filePath);
C#操作时代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; //using System.Collections; //using System.Collections.Specialized; namespace iniTest1 { public partial class Form1 : Form { [DllImport("kernel32")] // 写入ini文件操作section,key,value private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] // 读取ini文件操作section,key,和返回的keyvalue private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { openFileDialog1.ShowDialog(); textBox1.Text = openFileDialog1.FileName; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button2_Click(object sender, EventArgs e) { string FileName = textBox1.Text; string section = textBox2.Text; string key = textBox3.Text; string keyValue = textBox4.Text; try { //写入ini文件属性 WritePrivateProfileString(section, key, keyValue, FileName); MessageBox.Show("成功写入INI文件!", "信息"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button3_Click(object sender, EventArgs e) { StringBuilder temp = new StringBuilder(255); string FileName = textBox1.Text; string section = textBox2.Text; string key = textBox3.Text; //读取ini文件属性值---赋予当前属性上temp int i = GetPrivateProfileString(section, key, "无法读取对应数值!", temp, 255, FileName); //显示读取的数值 textBox4.Text = temp.ToString(); } } }