Récupération info com serie

Signaler
-
Messages postés
15402
Date d'inscription
mardi 11 mars 2003
Statut
Contributeur
Dernière intervention
19 janvier 2021
-
Bonjour,
Je suis en train de réaliser une petite application dans laquelle je dois lire les informations d'un des ports série de l'ordinateur. voici le code que j'ai pour l'instant :
 using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();                
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();                
                var tList = (from n in portnames join p in ports on n equals p["DeviceID"].ToString() select n + "-" + p["Caption"]).ToList();                        
                foreach (string s in tList)
                {
                    string[] trame = s.Split('-');                    
                    foreach (string word in trame)
                    {                       
                        if (trame[1].Substring(0, 16) == "Cypress USB UART")
                        {
                            serialPort1.PortName = trame[0];
                            label3.Text = s2 + serialPort1.PortName + s3;
                            drivecypress = 1;                           
                        }
                    }                    
                    //Driver Windows 10
                    if (trame[1].Contains("Cypress USB UART") == false) // no Cypress USB UART
                    {
                        PortName.Items.Clear();
                        foreach (string p in SerialPort.GetPortNames())
                            PortName.Items.Add(p);
                        if (PortName.Items.Count > 1)
                        {                           
                            PortName.SelectedIndex = 1;
                            PortName.Visible = true;
                            label3.Text = s7;                          
                        }
                   }
                    else PortName.Enabled = false;//PortName.Visible = false;              
                }                
            }

Mais avec ce code et suite a différent test, j'ai juste l'impression de ne récupéré aucune données dans la Tlist. Quelqu'un aurait une idée ?
(je travaille en C#, et le but de ce début de code est d'affichée dans un menu déroulant les ports com disponible)
EDIT : Ajout des balises de code (la coloration syntaxique).
Explications disponibles ICI

Merci d'y penser dans tes prochains messages.

1 réponse

Messages postés
15402
Date d'inscription
mardi 11 mars 2003
Statut
Contributeur
Dernière intervention
19 janvier 2021
502
Bonjour

essaye ça
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;

namespace Interface_Visibilimetre_Biral
{
    public class PortCom :INotifyPropertyChanged
    {

        private PortCom(ManagementObject Port)
        {
            Caption = Port["Caption"].ToString();
            Name = Port["Name"].ToString();
            CreationClassName = Port["CreationClassName"].ToString();
            Description = Port["Description"].ToString();
            DeviceID = Port["DeviceID"].ToString();
            Manufacturer = Port["Manufacturer"].ToString();
            PNPDeviceID = Port["PNPDeviceID"].ToString();
            Service = Port["Service"].ToString();
            Status = Port["Status"].ToString();
            SystemCreationClassName = Port["SystemCreationClassName"].ToString();
            SystemName = Port["SystemName"].ToString();
            CompatibleID = (string[])Port["CompatibleID"];
            ConfigManagerErrorCode = (UInt32)Port["ConfigManagerErrorCode"];
            ConfigManagerUserConfig = (bool)Port["ConfigManagerUserConfig"];
            HardwareID = (string[])Port["HardwareID"];

        }

        /// <summary>
        /// Nom du port au format COMX
        /// </summary>
        public string PortName
        {
            get
            {
                Match m = Regex.Match(Caption, @"\((?<PortName>COM\d+)\)");
                if (m.Success)
                    return m.Groups["PortName"].Value;
                return string.Empty;
            }
        }

        private string description;
        /// <summary>
        /// Description du port
        /// </summary>
        public string Description
        {
            get { return description; }
            set
            {
                if (value.MAJ(ref description))
                    RisePropertyChanged("Description");

            }
        }

        private string caption;
        public string Caption
        {
            get { return caption; }
            set
            {
                if (value.MAJ(ref caption))
                    RisePropertyChanged("Caption");

            }
        }


        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value.MAJ(ref name))
                    RisePropertyChanged("Name");

            }
        }

        private string creationClassName;
        public string CreationClassName
        {
            get { return creationClassName; }
            set
            {
                if (value.MAJ(ref creationClassName))
                    RisePropertyChanged("CreationClassName");

            }
        }

        private string deviceID;
        public string DeviceID
        {
            get { return deviceID; }
            set
            {
                if (value.MAJ(ref deviceID))
                    RisePropertyChanged("DeviceID");

            }
        }


        private string manufacturer;
        public string Manufacturer
        {
            get { return manufacturer; }
            set
            {
                if (value.MAJ(ref manufacturer))
                    RisePropertyChanged("Manufacturer");

            }
        }

        private string pNPDeviceID;
        public string PNPDeviceID
        {
            get { return pNPDeviceID; }
            set
            {
                if (value.MAJ(ref pNPDeviceID))
                    RisePropertyChanged("PNPDeviceID");

            }
        }

        private string service;
        public string Service
        {
            get { return service; }
            set
            {
                if (value.MAJ(ref service))
                    RisePropertyChanged("Service");

            }
        }

        private string status;
        public string Status
        {
            get { return status; }
            set
            {
                if (value.MAJ(ref status))
                    RisePropertyChanged("Status");

            }
        }

        private string systemCreationClassName;
        public string SystemCreationClassName
        {
            get { return systemCreationClassName; }
            set
            {
                if (value.MAJ(ref systemCreationClassName))
                    RisePropertyChanged("SystemCreationClassName");

            }
        }

        private string systemName;
        public string SystemName
        {
            get { return systemName; }
            set
            {
                if (value.MAJ(ref systemName))
                    RisePropertyChanged("SystemName");

            }
        }

        private int availability;
        public int Availability
        {
            get { return availability; }
            set
            {
                if (value.MAJ(ref availability))
                    RisePropertyChanged("Availability");

            }
        }

        private string[] compatibleID;
        public string[] CompatibleID
        {
            get { return compatibleID; }
            set
            {
                if (value.MAJ(ref compatibleID))
                    RisePropertyChanged("CompatibleID");

            }
        }

        private UInt32 configManagerErrorCode;
        public UInt32 ConfigManagerErrorCode
        {
            get { return configManagerErrorCode; }
            set
            {
                if (value.MAJ(ref configManagerErrorCode))
                    RisePropertyChanged("ConfigManagerErrorCode");

            }
        }

        private bool configManagerUserConfig;
        public bool ConfigManagerUserConfig
        {
            get { return configManagerUserConfig; }
            set
            {
                if (value.MAJ(ref configManagerUserConfig))
                    RisePropertyChanged("ConfigManagerUserConfig");

            }
        }

        private string[] hardwareID;
        public string[] HardwareID
        {
            get { return hardwareID; }
            set
            {
                if (value.MAJ(ref hardwareID))
                    RisePropertyChanged("HardwareID");

            }
        }
        
        /// <summary>
        /// Retourne la liste des ports Com présents
        /// </summary>
        public static List<PortCom> Liste
        {
            get
            {

                List<PortCom> liste = new List<PortCom>();
                ManagementObjectSearcher requete = new ManagementObjectSearcher("root\\CIMV2", "Select * FROM Win32_PnPEntity Where Caption like '%(COM%'");


                foreach (ManagementObject item in requete.Get())
                    liste.Add(new PortCom(item));


                return liste;
            }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void RisePropertyChanged(string Propriete)
        {
            if (this.PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(Propriete));
        }

        #endregion
    }
}