dotnet-读写ini配置文件-使用笔记

本文介绍如何使用C#处理ini配置文件,以保存和读取串口通讯参数和自定义指令。在软件启动时加载ini文件设置串口参数,并在关闭时更新文件。提供相关API文档链接及C#实现ini文件读写的参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平时我们做项目开发时,经常需要用一些上位机软件发送指令来做测试验证。用到串口通讯时,通讯参数我们希望每次打开时都能复用前次的,比如波特率、数据位、校验位、停止位。或者有一些自定义的常用指令保存在窗口上,不用每次打开软件都要自己去生成,比如电表测试常用指令:68 AA AA AA AA AA AA 68 13 00 DF 16。那么这种时候我们就可以使用ini配置文件。

本实例就是上面问题点的解决方式,每次打开软件时,都调用ini配置文件里面的参数去配置串口通讯参数,同时把要发送的命令显示在TextBox控件上。每次关闭软件时,都保存相应的参数、命令到ini配置文件。

窗口XAML代码如下:

<Window x:Class="IniFileDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:IniFileDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="270" Width="400" Loaded="Window_Loaded" Closed="Window_Closed">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="75" />
            <ColumnDefinition Width="50*" />
            <ColumnDefinition Width="23*"/>
        </Grid.ColumnDefinitions>
        <Label Content="串口号:" Grid.Row="0" Grid.Column="0" Width="70" Height="30" 
               HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5, 5, 0, 0" FontSize="14"  />
        <ComboBox x:Name="portComboBox" Grid.Row="0" Grid.Column="1" Width="100" Height="30" 
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="4.8,5,0,0" FontSize="14" />
        <Label Content="波特率:" Grid.Row="1" Grid.Column="0" Width="70" Height="30" 
               HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5, 5, 0, 0" FontSize="14"  />
        <ComboBox x:Name="baudComboBox" Grid.Row="1" Grid.Column="1" Width="100" Height="30" 
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="4.8,5,0,0" FontSize="14" />
        <Label Content="数据位:" Grid.Row="2" Grid.Column="0" Width="70" Height="30" 
               HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5,5.2,0,0" FontSize="14"  />
        <ComboBox x:Name="bitsComboBox" Grid.Row="2" Grid.Column="1" Width="100" Height="30" 
                  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="4.8,5.2,0,0" FontSize="14" />
        <Label Content="校验位:" Grid.Row="3" Grid.Column="0" Width="70" Height="30" 
               HorizontalAlignment="Left" VerticalAlignment="Top" Margin="5,5.2,0,0" FontSize="14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值