rutlean

Does anyone know of an easy way to check com port availability using System.IO.Ports in framework 2.0 I am looking for a way that should be easier than this:

public bool IsComAvailable(string com)

{

string sPort = @"\\.\COM" + com;

uint securityAttributes = 0;

IntPtr hPort;

bool now = cwSerial.IsOpen;

hPort = CreateFile(sPort,0,FILE_SHARE_READ | FILE_SHARE_WRITE,

securityAttributes, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

if (hPort.ToInt32() > 0)

{

Console.WriteLine("Com " + com + " Found");

CloseHandle(hPort);

return true;

}

return false;

}

Thanks



Re: Visual C# General Serial Com Port Availability

Jeremy Filburn

Code Snippet

System.IO.Ports.SerialPort s = new System.IO.Ports.SerialPort("COM1");

Console.WriteLine(s.IsOpen.ToString());






Re: Visual C# General Serial Com Port Availability

Peter Ritchie

Jeremy Filburn wrote:

Code Snippet

System.IO.Ports.SerialPort s = new System.IO.Ports.SerialPort("COM1");

Console.WriteLine(s.IsOpen.ToString());

That just tells you whether your application has a serial port open or not; it doesn't tell you if you can open the port or whether the port is valid or not.




Re: Visual C# General Serial Com Port Availability

Peter Ritchie

Use SerialPort.GetPortNames to get an array of port names for the current computer. It doesn't tell you anything about what's in use or not.




Re: Visual C# General Serial Com Port Availability

Jeremy Filburn

Rutlean,

Peter is right, as usual!

I thought you meant physically available assuming you did have a COM1 & COM2 port.

To get what is available like Peter said:

Code Snippet
string[] AvailableSerialPorts = System.IO.Ports.SerialPort.GetPortNames();

One way to find out if the port is available and can be opened is to try and open it.

My block of code above is not going to work until you open the serial object like so:

s.Open();

If your application cannot open the port, you will get an UnauthorizedAccessException. Open the port in a Try Catch block and all is good!

Sorry for my hasty answer