我有一个Windows C#应用程序。该应用程序通过串行端口连接到RFID卡读取器。尽管我默认给它提供了3个COM端口。我遇到了这样的情况:用户的端口不可用,而他的windows操作系统正在使用他的端口。
我的应用程序确实为用户提供了更改COM端口的能力,但要找到操作系统正在使用的COM端口,用户需要转到设备管理器并进行检查,这对于初学者来说可能不太方便。
有没有一个函数或方法可以准确地找到我的RFID卡在Windows中连接到哪个端口,这样我就可以简单地显示如下:
应用程序端口设置为:com....操作系统上的设备连接端口:COM....
另外,我的目标框架是3.5
编辑1:
尝试使用SerialPort.GetPortNames(),但返回一个空字符串: System.String[]..
我的射频识别设备列在设备管理器===>端口(COM& LPT)下面,显示为Silicon Labs USB to UART Bridge (COM3)
发布于 2014-08-18 22:11:18
Hi @user3828453如何?如果你仍然有一个空的端口,那么你可以使用返回的正确的端口号,而不是要求用户进入设备管理器并通过你的界面更新端口。
private static string GetRFIDComPort()
{
string portName = "";
for ( int i = 1; i <= 20; i++ )
{
try
{
using ( SerialPort port = new SerialPort( string.Format( "COM{0}", i ) ) )
{
// Try to Open the port
port.Open();
// Ensure that you're communicating with the correct device (Some logic to test that it's your device)
// Close the port
port.Close();
}
}
catch ( Exception ex )
{
Console.WriteLine( ex.Message );
}
}
return portName;
}发布于 2019-12-06 15:09:34
using System;
using System.Threading.Tasks;
namespace XYZ{
public class Program
{
public static void Main(string[] args)
{
Task<string> t = Task.Run( () =>
{
return FindPort.GetPort(10);
});
t.Wait();
if(t.Result == null)
Console.WriteLine($"Unable To Find Port");
else
Console.WriteLine($"[DONE] Port => {t.Result} Received");
// Console.ReadLine();
}
}
}using System;
using System.IO.Ports;
public static class FindPort
{
public static string GetPort(int retryCount)
{
string portString = null;
int count = 0;
while( (portString = FindPort.GetPortString() ) == null) {
System.Threading.Thread.Sleep(1000);
if(count > retryCount) break;
count++;
}
return portString;
}
static string GetPortString()
{
SerialPort currentPort = null;
string[] portList = SerialPort.GetPortNames();
foreach (string port in portList)
{
// Console.WriteLine($"Trying Port {port}");
if (port != "COM1")
{
try
{
currentPort = new SerialPort(port, 115200);
if (!currentPort.IsOpen)
{
currentPort.ReadTimeout = 2000;
currentPort.WriteTimeout = 2000;
currentPort.Open();
// Console.WriteLine($"Opened Port {port}");
currentPort.Write("connect");
string received = currentPort.ReadLine();
if(received.Contains("Hub"))
{
// Console.WriteLine($"Opened Port {port} and received {received}");
currentPort.Write("close");
currentPort.Close();
return port;
}
}
}
catch (Exception e)
{
//Do nothing
Console.WriteLine(e.Message);
if(currentPort.IsOpen)
{
currentPort.Write("close");
currentPort.Close();
}
}
}
}
// Console.WriteLine($"Unable To Find Port => PortLength : {portList.Length}");
return null;
}
}https://stackoverflow.com/questions/25354513
复制相似问题