C# 读写配置文件
利用 Windows API 读写配置文件。
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配置文件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了