C#ini文件读写实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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 ponentModel;
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();
}
}
}。