[英]How to get Bluetooth Device Com serial Port in winform C#?
[英]Finding the serial device COM port
我有一個 Windows C# 應用程序。 該應用程序通過串行端口連接到 RFID 讀卡器。 雖然我默認給它 COM 端口 3。 我遇到了用戶端口不可用並且他使用的端口與他的 Windows 操作系統不同的情況。
我的應用程序確實讓用戶能夠更改 COM 端口,但要找到他們的操作系統正在使用哪個 COM 端口,用戶需要轉到設備管理器並檢查,新手可能不習慣。
是否有一種功能或方法可以准確找到我的 RFID 卡在 Windows 中連接到的端口,以便我可以簡單地顯示如下:
應用程序端口設置為:COM .... 操作系統上的設備連接端口:COM ....
我的目標框架也是 3.5
編輯1:
嘗試使用 SerialPort.GetPortNames() 但它返回一個空字符串: System.String[]..
我的 RFID 設備在設備管理器 ===> 端口(COM 和 LPT)下列為 Silicon Labs CP210x USB 到 UART 橋接器 (COM3)
嗨@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;
}
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.