c# - Fastest way checking for COM ports -
i need check available com ports in application:
i created 2 ways this.
method 1:
public list<string> getallportsforeach() { var allports = new list<string>(); foreach (string portname in system.io.ports.serialport.getportnames()) { allports.add(portname); } return allports; }
method 2:
public list<string> getallportsforloop() { var allports = new list<string>(); (int = 1; <= 16; i++) { string comportname = "com" + convert.tostring(i); serialport sp = new serialport(comportname); try { sp.open(); allports.add(comportname); sp.close(); } catch { } } return allports; }
which fastest? should use , why?
the 1st one. reads available port names registry. more precise, enough use serialport.getportnames
, if you're not planning add custom port name list.
the 2nd one:
- limited port number (port name can "com20", total numbers of ports in system be, e.g., 4)
- exception-based (this ugly , slower).
Comments
Post a Comment