I am trying to find GSM modem in C#, using the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace LibUsbDotNet_Test1
{
class Program
{
static void Main(string[] args)
{
string[] ports = SerialPort.GetPortNames();
//display ports
for (int i = 0; i < ports.Length; i++)
{
Console.WriteLine(ports[i]);
}
//Find Modem
for (int i = 0; i < ports.Length; i++)
{
SerialPort p = new SerialPort(ports[i].Trim());
if (!p.IsOpen)
{
p.Open();
}
/**************nothing below this line get displayed***************************************/
if (CheckExistingModemOnComPort(p))
{
Console.WriteLine("Modem Found: " + p.PortName);
}
else
{
Console.WriteLine("No Modem Found: ");
}
p.Close();
}
Console.ReadLine();
}
private static bool CheckExistingModemOnComPort(SerialPort serialPort)
{
if ((serialPort == null) || !serialPort.IsOpen)
return false;
// Commands for modem checking
string[] modemCommands = new string[] { "AT", // Check connected modem. After 'AT' command some modems autobaud their speed.
"ATQ0" }; // Switch on confirmations
serialPort.DtrEnable = true; // Set Data Terminal Ready (DTR) signal
serialPort.RtsEnable = true; // Set Request to Send (RTS) signal
string answer = "";
bool retOk = false;
for (int rtsInd = 0; rtsInd < 2; rtsInd++)
{
foreach (string command in modemCommands)
{
serialPort.Write(command + serialPort.NewLine);
retOk = false;
answer = "";
int timeout = (command == "AT") ? 10 : 20;
// Waiting for response 1-2 sec
for (int i = 0; i < timeout; i++)
{
Thread.Sleep(100);
answer += serialPort.ReadExisting();
if (answer.IndexOf("OK") >= 0)
{
retOk = true;
break;
}
}
}
// If got responses, we found a modem
if (retOk)
return true;
// Trying to execute the commands without RTS
serialPort.RtsEnable = false;
}
return false;
}
}
}
the method CheckExistingModemOnComPort
is written by another Stack Overflow member here.
But, this code seems not to work after the line
if (!p.IsOpen)
{
p.Open();
}
This part is commented in the code, so you can identify the location easily. What is wrong here? I am closing the opened port as well.
Edit
This is the output I get
COM4
COM3
COM5
COM13
COM12
COM11
Here is the debug window output when this code comes into
if (!p.IsOpen)
{
p.Open();
}
My GSM modem (dongle) is at COM13
Update
I used try..catch() block to handle port opening, but now I get the message 'No Modem Found:' even though the com port for modem actually exists in the array.