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配置文件

posted @   double64  阅读(931)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示