@MaxMommersteeg if there is method such as DLL func ,WinApi it would be great.
It isn't hard getting the available COM ports, and it is easier than you think.
public List<string> GetAllAvailableComPorts()
{
return System.IO.Ports.SerialPort.GetPortNames().ToList();
}
Refer to Get Port Names Method (MSDN) for the GetPortnames method.
The code above will return you a List<string>
filled with all available COM ports.
You can call it with code below:
//Create new list<string>
List<string> availableComPorts = new List<string>();
//Fill list with list<string> returned from GetAllAvailableComports method.
availableComPorts = GetAllAvailableComports();
All COM ports in the list are available, and COM ports that are currently in use will not appear in the list. You can use the List<string> to check if COM1 is available. If so, you can connect to it, and if not, you can give the user a message that it is in use (users will get an "Acces denied" message when connecting to an unavailable port.)
I think you are using Windows Forms, since you tagged C# and SerialPort and I don't think ASP and WPF are able to use the SerialPort class (correct me if I am wrong). So I would create a listbox, filled with all available COM ports and let the user choose which COM port to use. The user isn't able to pick the wrong COM port, since they aren't in the list.
If you need more information about this, you can just leave a comment below. I still got enough code in head left since my last created application which used a serialport connection as well.
I would like to refer you to my own question below. It has some more information:
Get list of available COM ports