0

I would like to programmatically set the serial (COM) port settings (baud rate, stop bits etc) in my C# program.When I do something like the following, it does not save the settings in my windows environment. Am I totally on the wrong track?

  SerialPort serialPort = new SerialPort();
  string[] ports = SerialPort.GetPortNames();

  serialPort.PortName = "COM5";
  serialPort.BaudRate = 9600;
  serialPort.DataBits = 8;
  serialPort.DtrEnable = true;

  serialPort.StopBits = StopBits.One;
  serialPort.Parity = Parity.None;
  if (serialPort.IsOpen) serialPort.Close();
dsolimano
  • 8,870
  • 3
  • 48
  • 63
mcintoda
  • 635
  • 1
  • 8
  • 10
  • Why would it save the settings? Did you _ask_ it to save the settings? What if you hadn't wanted it to save the settings, and it did it anyway? – John Saunders Nov 02 '12 at 23:41
  • Are you trying to persist your settings between application starts or set them during runtime? Nothing you show here is saving anything. – Mark Hall Nov 02 '12 at 23:41
  • Question not obvious, please provide further info by responding to previous comments. – Ibrahim Najjar Nov 03 '12 at 00:04

1 Answers1

2

Go into your Project Property's Settings Tab and add the settings for the values you want to persist like this:

enter image description here

Then access them in your code like this. Saving them when your application closes:

public partial class Form1 : Form
{
    SerialPort serialPort; 
    public Form1()
    {
        InitializeComponent();
        serialPort = new SerialPort();
        serialPort.PortName = Properties.Settings.Default.PortName;
        serialPort.BaudRate = Properties.Settings.Default.BaudRate;
        serialPort.DataBits = Properties.Settings.Default.DataBits;
        serialPort.DtrEnable = Properties.Settings.Default.DtrEnable;
        serialPort.StopBits = Properties.Settings.Default.StopBits;
        serialPort.Parity = Properties.Settings.Default.Parity;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        serialPort.PortName = "COM1";
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Properties.Settings.Default.PortName = serialPort.PortName;
        Properties.Settings.Default.BaudRate = serialPort.BaudRate;
        Properties.Settings.Default.DataBits = serialPort.DataBits;
        Properties.Settings.Default.DtrEnable = serialPort.DtrEnable;
        Properties.Settings.Default.StopBits = serialPort.StopBits;
        Properties.Settings.Default.Parity = serialPort.Parity;
        Properties.Settings.Default.Save(); //Saves settings 

    }
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111