C#读写配置文件

利用 Windows API 读写配置文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CS读写配置文件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("kernel32")]//读配置文件方法的6个参数:所在的分区(section)、 键值、 初始缺省值、 StringBuilder、 参数长度上限 、配置文件路径
public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32")]//配置文件方法的4个参数: 所在的分区(section)、 键值、 参数值、 配置文件路径
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

/*读配置文件*/
public static string GetValue(string section, string key)
{
// ▼ 获取当前程序启动目录
string strPath = Application.StartupPath + @"/config.ini";
if (File.Exists(strPath)) {
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "配置文件不存在,读取未成功!", sb, 255, strPath);

return sb.ToString();
}
else {
return string.Empty;
}
}
/*写配置文件*/
public static void SetValue(string section, string key, string value)
{
// ▼ 获取当前程序启动目录
string strPath = Application.StartupPath + @"/config.ini";
WritePrivateProfileString(section, key, value, strPath);
}

private void Form1_Load(object sender, EventArgs e)
{
SetValue("参数", "波特率", "9600"); // 都是字符串类型
SetValue("参数", "率特波", "110"); // 都是字符串类型
}

private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text += GetValue("参数", "波特率");
richTextBox1.Text += "\n";
richTextBox1.Text += GetValue("参数", "率特波");
}
}
}

界面:

运行,点击 button:

config.ini配置文件内容如下:




参考:
1.link-01 // Windows API 读写配置文件
2.link-02 // 在C#中读写INI配置文件

感谢支持!