设为首页 加入收藏

TOP

获取串口映射的COM端口号(一)
2018-01-17 13:05:19 】 浏览:209
Tags:获取 串口 映射 COM 口号

背景:近期由于项目需要,需要操作短信猫,当短信猫插入电脑后,会根据当前PC状况,映射COM口,这里需动态获取短信猫映射的COM端口号。


编程语言C#:


具体代码如下


public enum HardwareEnum
        {
            Win32_PnPEntity // 所有设备
        }


        /// <summary>
        /// 获取相应COM口号
        /// </summary>
        private static string getComInfo(HardwareEnum hardType, string propkey)
        {
            List<string> deviceslist = new List<string>();
            StringBuilder comsb = new StringBuilder();


            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select *from " + hardType))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {


                  Object deviceprop=hardInfo.Properties[propkey].Value;
                  if (deviceprop!=null&&deviceprop.ToString().Contains("COM"))  //避免出现空设备值异常
                        {
                            deviceslist.Add(hardInfo.Properties[propkey].Value.ToString());
                        }
                    }
                    searcher.Dispose();
                }
                string[] devicestemps = deviceslist.ToArray();


                foreach (string device in devicestemps)
                {
                    if (device.Contains("AT")) //这里短信猫需操作AT口
                    {
                        int index = device.IndexOf("(");
                        string devicetemp = device.Substring(index + 4); //得到形如"3)"形式
                        string comnum = devicetemp.Substring(0, devicetemp.Length - 1); //直接得到相应COM端口号
                        comsb.Append(comnum + "*");  //用“*”号隔开,当出现多个的时候
                    }
                }


                string comsbstring=comsb.ToString();
                return comsbstring.Substring(0, comsbstring.Length - 1); //移除最后一个“*”号


     

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇开地址哈希表(Hash Table)的接.. 下一篇使用Netty3或Netty4发布Http协议..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目