我已经构建了使用串口C#的应用程序表单。
当我关闭可执行文件时,我想在.ini文件中保存上一次使用的序列号和COM数据。因此,我可以在下一次使用应用程序时使用相同的数据。
private void btnSave_Click(object sender, EventArgs e)
{
try
{
_Ser.PortName = cBoxPort.Text;
_Ser.BaudRate = Convert.ToInt32(cBoxBaud.Text);
_Ser.DataBits = Convert.ToInt32(cBoxDatabits.Text);
_Ser.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cBoxStopBits.Text);
_Ser.Parity = (Parity)Enum.Parse(typeof(Parity), cBoxParitybits.Text);
this.Close();
string[] data = { cBoxPort.Text, cBoxDatabits.Text, cBoxStopBits.Text, cBoxParitybits.Text };
}
catch (Exception err)
{
MessageBox.Show(err.Message, ("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Configuration has been saved","Status");
}发布于 2022-10-20 11:39:06
我认为最好的方法是用要保存的数据序列化对象并检索它,只需反序列化对象。
下面是如何使用XML文件How to serialize/deserialize simple classes to XML and back来执行此操作的示例
一个简单的方法是使用JSON,下面是一个应用于您的代码的示例。
您将需要引用Newtonsoft.Json;
_Ser.PortName = cBoxPort.Text;
_Ser.BaudRate = Convert.ToInt32(cBoxBaud.Text);
_Ser.DataBits = Convert.ToInt32(cBoxDatabits.Text);
_Ser.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cBoxStopBits.Text);
_Ser.Parity = (Parity)Enum.Parse(typeof(Parity), cBoxParitybits.Text);将对象序列化为.json文件
string dataFile = @"c:\DataFile.json";
string jsonString = JsonConvert.SerializeObject(_Ser);
File.WriteAllText(dataFile, jsonString);从.json文件检索数据
string recoverdata = File.ReadAllText(dataFile);
_Ser = JsonConvert.DeserializeObject<[put here the type of your object "_ser"] >(recoverdata);发布于 2022-10-20 11:54:41
您需要生成一个json,然后保存上次在该json上提交的端口。当程序打开时,您应该从json读取最后记录的端口,然后再次打开端口。
https://stackoverflow.com/questions/74139150
复制相似问题