Winform中实现保存配置到文件/项目启动时从文件中读取配置(序列化与反序列化对象)
迪丽瓦拉
2025-05-29 17:24:21
0

场景

Winform中实现序列化指定类型的对象到指定的Xml文件和从指定的Xml文件中反序列化指定类型的对象:

Winform中实现序列化指定类型的对象到指定的Xml文件和从指定的Xml文件中反序列化指定类型的对象_winform xml序列化_霸道流氓气质的博客-CSDN博客

上面讲的序列化对象的流程需要进行补充。

Winform程序需要将某些动态配置的TextBox的内容在配置后进行保存,下次启动时仍然读取加载显示之前的配置。

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主

实现

1、新建配置项对象类,属性根据要保存的内容对应而定。

    [Serializable]public class DataConfig{/// /// 煤矿编码/// public string MineCode { get; set; }/// /// 煤业公司编码/// public string CompanyCode { get; set; }/// /// http地址/// public string HttpAddress { get; set; }/// /// MqttIp/// public string MqttIp { get; set; }/// /// MqttPort/// public string MqttPort { get; set; }/// /// MqttUsername/// public string MqttUsername { get; set; }/// /// MqttPassword/// public string MqttPassword { get; set; }}

注意要在类上添加

[Serializable]

2、然后新建序列化对象的工具类SerializeXmlHelper

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;namespace DataConvert.dataconvert
{class SerializeXmlHelper{/// /// 序列化指定类型的对象到指定的Xml文件/// /// 要序列化的对象类型/// 要序列化的对象/// 保存对象数据的完整文件名public static void SerializeXml(T obj, string xmlFileName){lock (xmlFileName){try{string dir = Path.GetDirectoryName(xmlFileName);       //获取文件路径if (!Directory.Exists(dir)){Directory.CreateDirectory(dir);}string xmlContent = SerializeObject(obj);FileHelper.WriteFile(xmlFileName, xmlContent, Encoding.UTF8);}catch (Exception ex){Console.Write(ex);}}}/// /// 把对象序列化为xml字符串/// /// /// /// public static string SerializeObject(T obj){if (obj != null){StringWriter strWriter = new StringWriter();XmlSerializer serializer = new XmlSerializer(typeof(T));serializer.Serialize(strWriter, obj);return strWriter.ToString();}else{return String.Empty;}}/// /// 从指定的Xml文件中反序列化指定类型的对象/// /// 反序列化的对象类型/// 保存对象数据的文件名/// 返回反序列化出的对象实例public static T DeserializeXml(string xmlFileName){lock (xmlFileName){try{if (!File.Exists(xmlFileName)){Console.Write("序列化文件不存在!");return default(T);}else{string xmlContent = FileHelper.ReadFile(xmlFileName, Encoding.UTF8);T obj = DeserializeObject(xmlContent);return obj;}}catch (Exception ex){Console.Write(ex);return default(T);}}}/// /// 把xml字符串反序列化为对象/// /// /// /// public static T DeserializeObject(string xmlString){if (!String.IsNullOrEmpty(xmlString)){StringReader strReader = new StringReader(xmlString);XmlSerializer serializer = new XmlSerializer(typeof(T));T obj = (T)serializer.Deserialize(strReader);return obj;}else{return default(T);}}/// /// 向指定文件写入内容/// /// 要写入内容的文件完整路径/// 要写入的内容/// 编码格式public static void WriteFile(string path, string content, System.Text.Encoding encoding){try{object obj = new object();if (!File.Exists(path)){FileStream fileStream = File.Create(path);fileStream.Close();}lock (obj){using (StreamWriter streamWriter = new StreamWriter(path, false, encoding)){streamWriter.WriteLine(content);streamWriter.Close();streamWriter.Dispose();}}}catch (Exception ex){Console.Write(ex);}}}
}

部分方法中用到了文件操作的相关工具类方法,所以新建文件操作工具类FileHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DataConvert.com.bdtd.dataconvert
{class FileHelper{/// /// 向指定文件写入内容/// /// 要写入内容的文件完整路径/// 要写入的内容public static void WriteFile(string path, string content){try{object obj = new object();if (!System.IO.File.Exists(path)){System.IO.FileStream fileStream = System.IO.File.Create(path);fileStream.Close();}lock (obj){using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(path, false, System.Text.Encoding.Default)){streamWriter.WriteLine(content);streamWriter.Close();streamWriter.Dispose();}}}catch (Exception ex){Console.WriteLine(ex.Message);}}/// /// 向指定文件写入内容/// /// 要写入内容的文件完整路径/// 要写入的内容/// 编码格式public static void WriteFile(string path, string content, System.Text.Encoding encoding){try{object obj = new object();if (!System.IO.File.Exists(path)){System.IO.FileStream fileStream = System.IO.File.Create(path);fileStream.Close();}lock (obj){using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(path, false, encoding)){streamWriter.WriteLine(content);streamWriter.Close();streamWriter.Dispose();}}}catch (Exception ex){Console.WriteLine(ex.Message);}}/// /// 读取文件内容/// /// 要读取的文件路径/// 编码格式/// 返回文件内容public static string ReadFile(string path, System.Text.Encoding encoding){string result;if (!System.IO.File.Exists(path)){result = "不存在相应的目录";}else{System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, encoding);result = streamReader.ReadToEnd();streamReader.Close();streamReader.Dispose();}return result;}}
}

3、序列化对象到文件

这里可以在按钮的点击事件或者窗体的closing事件中获取到各textBox的内容并序列化到xml文件中

        private void button_save_config_Click(object sender, EventArgs e){//保存配置到文件try {saveConfigToFile();MessageBox.Show("配置保存成功");} catch (Exception ex) {MessageBox.Show("配置保存失败:"+ex.Message);}           }

具体执行的方法

        private void saveConfigToFile() {try {DataConfig dataConfig = new DataConfig();dataConfig.MineCode = textBox_mine_code.Text.Trim();dataConfig.CompanyCode = textBox_company_code.Text.Trim();dataConfig.HttpAddress = textBox_origin_address.Text.Trim();dataConfig.MqttIp = textBox_target_address.Text.Trim();dataConfig.MqttPort = textBox_mqtt_port.Text.Trim();dataConfig.MqttUsername = textBox_mqtt_username.Text.Trim();dataConfig.MqttPassword = textBox_mqtt_password.Text.Trim();string path = configFilePath;SerializeXmlHelper.SerializeXml(dataConfig, path);} catch(Exception ex) {textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":保存配置到文件失败:" + ex.Message);textBox_log.AppendText("\r\n");}}

前面都是获取textBox中的输入内容,后面两行才是进行序列化对象的实现。

文件的路径提前声明变量

        //配置文件存放路径private string configFilePath = Application.StartupPath + "\\config\\config.xml";

这里将配置文件放在启动目录下的config下的config.xml中

4、反序列化配置文件到对象

可以在窗体的load时间中读取配置文件并反序列化到对象,然后给各控件赋值。

        private void Form1_Load(object sender, EventArgs e){//从配置文件读取配置readConfigFromFile();}

实现方法

        //从配置文件读取配置private void readConfigFromFile(){try {DataConfig dataConfig = new DataConfig();string path = configFilePath;if (File.Exists(path)) {dataConfig = SerializeXmlHelper.DeserializeXml(path);textBox_mine_code.Text = dataConfig.MineCode;textBox_company_code.Text = dataConfig.CompanyCode;textBox_origin_address.Text = dataConfig.HttpAddress;textBox_target_address.Text = dataConfig.MqttIp;textBox_mqtt_port.Text = dataConfig.MqttPort;textBox_mqtt_username.Text = dataConfig.MqttUsername;textBox_mqtt_password.Text = dataConfig.MqttPassword;}} catch(Exception ex) {textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":从配置文件读取配置失败:" + ex.Message);textBox_log.AppendText("\r\n");}}

注意这里要规避首次加载没有配置文件或者人为删除配置文件的情况,需要加判断。

其次上面在新建xml文件中,也对config路径做了判断,如果不存在则创建。

相关内容

热门资讯

linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
C++ 机房预约系统(六):学... 8、 学生模块 8.1 学生子菜单、登录和注销 实现步骤: 在Student.cpp的...
A.机器学习入门算法(三):基... 机器学习算法(三):K近邻(k-nearest neigh...
数字温湿度传感器DHT11模块... 模块实例https://blog.csdn.net/qq_38393591/article/deta...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
Redis 所有支持的数据结构... Redis 是一种开源的基于键值对存储的 NoSQL 数据库,支持多种数据结构。以下是...
win下pytorch安装—c... 安装目录一、cuda安装1.1、cuda版本选择1.2、下载安装二、cudnn安装三、pytorch...
MySQL基础-多表查询 文章目录MySQL基础-多表查询一、案例及引入1、基础概念2、笛卡尔积的理解二、多表查询的分类1、等...
keil调试专题篇 调试的前提是需要连接调试器比如STLINK。 然后点击菜单或者快捷图标均可进入调试模式。 如果前面...
MATLAB | 全网最详细网... 一篇超超超长,超超超全面网络图绘制教程,本篇基本能讲清楚所有绘制要点&#...
IHome主页 - 让你的浏览... 随着互联网的发展,人们越来越离不开浏览器了。每天上班、学习、娱乐,浏览器...
TCP 协议 一、TCP 协议概念 TCP即传输控制协议(Transmission Control ...
营业执照的经营范围有哪些 营业执照的经营范围有哪些 经营范围是指企业可以从事的生产经营与服务项目,是进行公司注册...
C++ 可变体(variant... 一、可变体(variant) 基础用法 Union的问题: 无法知道当前使用的类型是什...
血压计语音芯片,电子医疗设备声... 语音电子血压计是带有语音提示功能的电子血压计,测量前至测量结果全程语音播报࿰...
MySQL OCP888题解0... 文章目录1、原题1.1、英文原题1.2、答案2、题目解析2.1、题干解析2.2、选项解析3、知识点3...
【2023-Pytorch-检... (肆十二想说的一些话)Yolo这个系列我们已经更新了大概一年的时间,现在基本的流程也走走通了,包含数...
实战项目:保险行业用户分类 这里写目录标题1、项目介绍1.1 行业背景1.2 数据介绍2、代码实现导入数据探索数据处理列标签名异...
记录--我在前端干工地(thr... 这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 前段时间接触了Th...
43 openEuler搭建A... 文章目录43 openEuler搭建Apache服务器-配置文件说明和管理模块43.1 配置文件说明...