Beispiel #1
0
        /*
         * 查找包含多个关键字符串的第一个串口
         * 例如要找出CH340串口号是多少: 其串口名称为"USB-SERIAL CH340 (COM8)", 关键字符串为"SERIAL"和"CH340", 则函数返回"COM8"
         */
        public static string FindComByKeyStr(string[] keyStr)
        {
            string comName = null;

            //串口枚举, 获取每个串口名称的字符串数组
            if (keyStr != null)
            {
                string[] CurSerialPort = SerialEnumPort.enumSerialPortGetName();
                if (CurSerialPort != null)
                {
                    foreach (string str in CurSerialPort)
                    {
                        bool isContanKey = true;
                        foreach (string ketstr in keyStr)
                        {
                            if (!str.Contains(ketstr))
                            {
                                isContanKey = false;
                                break;
                            }
                        }
                        if (isContanKey)                                        //若名称包含关键字符串
                        {
                            int leftBracketIndex = 0;
                            try { leftBracketIndex = str.LastIndexOf("("); }
                            catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                            if (leftBracketIndex != 0)
                            {
                                int tmp = 0;
                                if (int.TryParse(str.Substring(leftBracketIndex + 5, 1), out tmp))
                                {
                                    comName = str.Substring(leftBracketIndex + 1, 5);
                                }
                                else
                                {
                                    comName = str.Substring(leftBracketIndex + 1, 4);
                                }
                                break;
                            }
                        }
                    }
                }
            }

            return(comName);
        }