How can I select and change COM port using XML file on my c# application?

53 views Asked by At

I have a c# windows application that uses the available debug board COM port to run.

I want to create a settings.xml file so the COM port is picked by the application using xml file instead of using hard coded COM port number (example: string command = "command filename.py... COM16 ...command").

1

There are 1 answers

4
Slepoyi On

Create your settings.xml. For example, it has the following structure:

<?xml version="1.0"?>
<COMSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Port>COM16</Port>
</COMSettings>

Create the class to deserialize your xml into it:

public class COMSettings
{
    public string Port { get; set; };

    // some other data if needed
 
    public COMSettings() { }
    public COMSettings(string port)
    {
        Port = port;
    }
}

The usage is simple - read and deserialize xml and then just use your port value.

using System.Xml.Serialization;

...

// somewhere in your app
var xmlSerializer = new XmlSerializer(typeof(COMSettings));

using (var fs = new FileStream("settings.xml", FileMode.OpenOrCreate));

var settings = xmlSerializer.Deserialize(fs) as COMSettings;

// usage
var command = $"command filename.py {settings.Port}";