c# – 使用VID和PID识别连接到x64的USB设备的COM端口

前端之家收集整理的这篇文章主要介绍了c# – 使用VID和PID识别连接到x64的USB设备的COM端口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如下我能够通过给定的pid和vid获得附加到32位win7OS机器的usb com端口名称,但是当在x64中运行时它会卡在以下行中:
comports.Add((string)rk6.GetValue("PortName"));

这是我的代码

static List<string> ComPortNames(String VID,String PID)
    {
        String pattern = String.Format("^VID_{0}.PID_{1}",VID,PID);
        Regex _rx = new Regex(pattern,RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();

        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");

        foreach (String s3 in rk2.GetSubKeyNames())
        {

            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        comports.Add((string)rk6.GetValue("PortName"));
                    }
                }
            }
        }
        return comports;
    }

实际代码得到here,那么如何在x64中获取com端口名称,有什么建议吗?

解决方法

通过阅读您的代码,我发现您在注册表中查看的当前路径不包含任何有关端口的信息.
但我找到了一种通过做这个小改变来阅读它的方法
static List<string> ComPortNames(String VID,RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();

        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");

        foreach (String s3 in rk2.GetSubKeyNames())
        {

            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        string location = (string)rk5.GetValue("LocationInformation");
                        if (!String.IsNullOrEmpty(location))
                        {
                            string port = location.Substring(location.IndexOf('#') + 1,4).TrimStart('0');
                            if (!String.IsNullOrEmpty(port)) comports.Add(String.Format("COM{0:####}",port));
                        }
                        //RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        //comports.Add((string)rk6.GetValue("PortName"));
                    }
                }
            }
        }
        return comports;
    }

它做得很好.谢谢你的代码,顺便说一句……它给了我很多帮助!

原文链接:https://www.f2er.com/csharp/97469.html

猜你在找的C#相关文章