C#中读写配置参数文件(利用Windows的API)

时间:2023-03-09 19:28:45
C#中读写配置参数文件(利用Windows的API)
读配置文件与写配置文件的核心代码如下:
 [DllImport("kernel32")]
// 读配置文件方法的6个参数:所在的分区(section)、键值、 初始缺省值、 StringBuilder、 参数长度上限、配置文件路径
private static extern int GetPrivateProfileString(string section, string key, string deVal, StringBuilder retVal,
int size, string filePath); [DllImport("kernel32")]
// 写配置文件方法的4个参数:所在的分区(section)、 键值、 参数值、 配置文件路径
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); public static void SetValue(string section, string key, string value)
{
//获得当前路径,当前是在Debug路径下
string strPath = Environment.CurrentDirectory + "\\system.ini";
WritePrivateProfileString(section, key, value, strPath);
} public static string GetValue(string section, string key)
{
StringBuilder sb = new StringBuilder();
string strPath = Environment.CurrentDirectory + "\\system.ini";
//最好初始缺省值设置为非空,因为如果配置文件不存在,取不到值,程序也不会报错
GetPrivateProfileString(section, key, "配置文件不存在,未取到参数", sb, , strPath);
return sb.ToString(); }
【应用举例】

功能说明:程序加载时,创建配置文件并往里面写入波特率参数。(配置文件不需要事先存在,此Windows的API会自动创建)。点击button1,将取到的波特率显示到textBox1中。

完整代码如下:

 using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} [DllImport("kernel32")]
// 读配置文件方法的6个参数:所在的分区(section)、键值、 初始缺省值、 StringBuilder、 参数长度上限、配置文件路径
private static extern int GetPrivateProfileString(string section, string key, string deVal, StringBuilder retVal,
int size, string filePath); [DllImport("kernel32")]
// 写配置文件方法的4个参数:所在的分区(section)、 键值、 参数值、 配置文件路径
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); public static void SetValue(string section, string key, string value)
{
//获得当前路径,当前是在Debug路径下
string strPath = Environment.CurrentDirectory + "\\system.ini";
WritePrivateProfileString(section, key, value, strPath);
} public static string GetValue(string section, string key)
{
StringBuilder sb = new StringBuilder();
string strPath = Environment.CurrentDirectory + "\\system.ini";
//最好初始缺省值设置为非空,因为如果配置文件不存在,取不到值,程序也不会报错
GetPrivateProfileString(section, key, "配置文件不存在,未取到参数", sb, , strPath);
return sb.ToString(); } private void Form1_Load(object sender, EventArgs e)
{
SetValue("参数","波特率","");
} private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = GetValue("参数", "波特率");
} }
}

程序界面:

C#中读写配置参数文件(利用Windows的API)

C#中读写配置参数文件(利用Windows的API)

C#中读写配置参数文件(利用Windows的API)