C# 读写配置文件
2021-09-17 16:41:04

利用 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 += "
";
            richTextBox1.Text += GetValue("参数", "率特波");
        }
    }
}

界面:

运行,点击 button:

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




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

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......