C#获取串口的几种方式

摘要#

使用C#获取串口最简单的方式就是通过SerialPort对象了,但有时并不能满足需求,比如有些串口是通过驱动模拟的,那这种可能就获取不到了。

示例代码#

这里简单演示几种常用的本机串口获取方式:

通过SerialPort对象获取
SerialPort.GetPortNames().ToList();
通过查注册外表方式获取
private List<string> GetPortDeviceName()
        {
            var comlist = new List<string>();
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    comlist.Add(sValue);
                }
            }
            return comlist;
        }
通过ManagementObjectSearcher对象方式获取
private List<string> GetComList()
        {
            var comlist = new List<string>();
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties["Name"].Value != null && hardInfo.Properties["Name"].Value.ToString().Contains("(COM"))
                        {
                            String strComName = hardInfo.Properties["Name"].Value.ToString();
                            comlist.Add(strComName);
                        }
                    }
                }
                Console.ReadKey();
            }
            catch
            {
            }
            return comlist;
        }

通常情况下使用第一种方式就可以实现,按照实际情况自行取舍即可。

效果#

image-20230303231543762

虚拟串口工具#

工具下载地址:https://luc-files.oss-cn-shenzhen.aliyuncs.com/Tools/VSPD虚拟串口工具.zip

作者:傲慢与偏见

出处:https://www.cnblogs.com/chonglu/p/17177350.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

声明:如果本文对您有帮助,请点击【推荐】您的赞赏将鼓励我继续创作!想跟我一起进步么?那就【关注】我吧

posted @   傲慢与偏见luc  阅读(4572)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示