C# 写配置文件(cfg)中的内容

文章介绍了如何使用C#的DllImport方法调用kernel32库,通过WritePrivateProfileString和GetPrivateProfileString函数来读写配置文件(app.cfg)中General段下的Port端口值,展示了一个从读取8000到写入8004,再读取确认的过程。
摘要由CSDN通过智能技术生成

C# 写配置文件(cfg)中的内容

1.如下图所示,假如我们想要在代码中改变General下的Port端口值,那么需要如下步骤:
在这里插入图片描述
2.在program类中添加如下几句代码:

        using System.Runtime.InteropServices;(引用)
        [DllImport("kernel32")]
        public static extern int WritePrivateProfileString(string section, string key, string str, string filePath);

3.完整代码如下:刚开始我们读配置文档中串口的值为8000,后面写成8004,再次读串口的值会发现已经变成了8004.
在program.cs类中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.Runtime.InteropServices;

namespace AOI_demo
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]

        #region 读配置文档中的内容
        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        #endregion

        #region 写配置文档中的内容
        [DllImport("kernel32")]
        public static extern int WritePrivateProfileString(string section, string key, string str, string filePath);
        #endregion

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form2());
        }
    }
}

在窗体程序中:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AOI_demo
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            #region 读配置文档中串口的值
            string path = Application.StartupPath + @"\app.cfg";//配置文档中的地址
            StringBuilder sb = new StringBuilder(512);
            Program.GetPrivateProfileString("General", "Port", "", sb, 512, path);
            string str = sb.ToString();//str=8000
            Console.WriteLine(str);
            #endregion

            #region 向配置文档中写值
            Program.WritePrivateProfileString("General", "Port", "8004", path);//写值
            #endregion


            #region 再次读值
            Program.GetPrivateProfileString("General", "Port", "", sb, 512, path);
            str = sb.ToString();//str=8004
            Console.WriteLine(str);
            #endregion


        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值