Search code examples
c#serial-port

Serial port data savings in .ini file C#


I have built application forms that use a serial port C#.

I want to save the last serial port number used and COM data in the .ini file when I close the executable. So, I can use the same data for the next use of the application

        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");
    }

Solution

  • I think the best way is for you to serialize the object with the data you want to save and to retrieve it, just deserialize the object.

    Here is an example of how to do it with XML file:How to serialize/deserialize simple classes to XML and back

    A simpler way is with JSON, here is an example applied to your code.

    You will need the reference 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);
    

    Serializing the object to a .json file

    string dataFile = @"c:\DataFile.json";
            string jsonString = JsonConvert.SerializeObject(_Ser);
            File.WriteAllText(dataFile, jsonString);
    

    Retrieving data from a .json file

    string recoverdata =  File.ReadAllText(dataFile);
            _Ser = JsonConvert.DeserializeObject<[put here the type of your object "_ser"] >(recoverdata);