Im trying to make my software choose witch com ports to use from the Configuration file. I haven't had any luck so far, just to be clear, im just a newbie in C# but eager to learn more. I have 4 com ports that will send a command to various micro controllers.
So far i have been using this code to define witch com ports to use and its settings:SerialPort SerialPort1 = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
SerialPort SerialPort2 = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One);
SerialPort SerialPort3 = new SerialPort("COM3", 19200, Parity.None, 8, StopBits.One);
SerialPort SerialPort5 = new SerialPort("COM4", 19200, Parity.None, 8, StopBits.One);
And an button to trigger it:
private void button1_ON_Click(object sender, EventArgs e)
{
try
{
if (!(SerialPort1.IsOpen))
SerialPort1.Open();
SerialPort1.Write(new byte[] { 0xFF, 0x01, 0x01 }, 0, 3);
SerialPort1.Close();
timer1.Interval = 500;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(OnTimerEvent1);
}
catch (Exception ex)
{
MessageBox.Show("Error writing to serial." + ex.Message, "OH NO AN ERROR!!");
}
}
I have read a lot into create a config file to define its values, but i just cant seem to get it to work with the seri开发者_JAVA技巧alport. Have you got any suggestions how to implement this to my code?
Thanks
you can put the active port's number (port that is to be used) in appSettings
section of config file. Then you can use ConfigurationManger
class to get values from app settings.
Config File:
<appSettings>
<add key="activePort" value="COM3" />
</appSettings>
Code:
var port=ConfigurationManager.AppSettings["activePort"]
For multiple ports you can use comma separated values like "COM1,COM3" and then split it.
For more information check this MSDN page:
精彩评论