1

I have some code i wrote for finding the COM-Port of a certain Motor-Controller, based off of this Article: Getting Serial Port Information

Since this Code doesn´t explicitely look for ComPorts, but for Device Names and Infos, I played around a bit and found out that when you look for a certain device in the resulting list, referenced by name, and write that to a *.txt file, the COMPort shows up in (brackets) after the name, like so: Devicename (COM5).

This I used to write that information to a string using Array.Find, and from then on it´s just selecting the number to connect to.

My Problem is that i don´t want to loop through ALL devices, but just until the one I´m looking for is found, and then break the loop.

This, however, results in a string[1] Array without the COMPort attached to entries, opposed to a string[2] Array with ComPort attached if I don´t break the loop.

I want to know why the COMPort gets attached in the first place (my guess is collection.Dispose), and why breaking the loop kills that "function/bug/whatever".

{

    public static void ComPortSelectionMain(/*string[] args*/)
    {
        string ComDummy; // ComPort, ComPortString;
        int ComNumber = 0;
        var usbDevices = GetUSBDevices();
        var ComList = new List<string>();


        foreach (var usbDevice in usbDevices)
        {
            if (usbDevice.Description == "PI C-863")
            {
                //Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}", usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
                ComList.Add(usbDevice.Name);        //Add USB Device
            }
        }

        var ComArray = ComList.ToArray();
        var target = "PI C-863 (COM";
        // var target2 = ")";
        int arrayindex = 0;
        int start = 0, stop = 0;
        string targetname = "PI C-863";

        string test = (Array.Find(ComArray, element => element.Contains(targetname)));
        //Console.WriteLine("Test: " + test);
        if (test == targetname)                //look if comarray contains target
        {
            //int index = Array.FindIndex(ComArray, item => item == "(");         // row.Contains(targetname));
            int indexsigned = Array.IndexOf(ComArray, target);
            int index = Math.Abs(indexsigned);
            start = ComArray[index].IndexOf('(') + 1;
            arrayindex = index;
            stop = ComArray[index].IndexOf(')');
        }

        int COMlength = 0, portlength = 0, pos = 0;
        COMlength = stop - start;
        portlength = stop - start - 3;
        pos = start + 3;
        //Console.WriteLine("COM: {0}", ComArray[arrayindex]);
        ComDummy = ComArray[arrayindex].Substring(start, COMlength);
        //Console.WriteLine("ComDummy: {0}", ComDummy);
        ComNumber = Convert.ToInt32(ComArray[arrayindex].Substring(pos, portlength));
        Console.WriteLine("ComPort Number: {0}", ComNumber);

        Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
        List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

        ManagementObjectCollection collection;
        using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
            collection = searcher.Get();

        bool kappa = true;
        foreach (var device in collection)
        {
            devices.Add(new USBDeviceInfo(
            (string)device.GetPropertyValue("DeviceID"),
            (string)device.GetPropertyValue("PNPDeviceID"),
            (string)device.GetPropertyValue("Description"),
            (string)device.GetPropertyValue("Name"),
            (string)device.GetPropertyValue("Service")
            ));

            ***//if ((devices.Exists(element => element.Description == "PI C-863")) && kappa)
            //{
            //    Console.WriteLine("Found PI C-863!");
            //    kappa = false;
            //    //break;
            //}***  <<< THIS IF() BREAKS MY CODE
        }

        collection.Dispose();
        return devices;
    }
}

class USBDeviceInfo
{
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string name, string var)
    {
        this.DeviceID = deviceID;
        this.PnpDeviceID = pnpDeviceID;
        this.Description = description;
        this.Name = name;
        this.Var = var;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
    public string Name { get; private set; }
    public string Var { get; private set; }
}

The if(devices.Exist) question breaks my code if I use it and let if break the loop, can somebody explain why, and what i could do? (Code works fine so far, but not being able to break the loop slows it down quite a bit)

Thanks in advance :)

Regards, Cinnabar

Community
  • 1
  • 1
Cinnabar
  • 11
  • 1

2 Answers2

0

You should try :

static List<USBDeviceInfo> GetUSBDevices()
{
    ManagementObjectCollection collection;
    using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();

    foreach (var device in collection)
    {
        if(device.GetPropertyValue("Description").Equals("PI C-863"))
        {
             Console.WriteLine("Found PI C-863!");
             break;
        }

    }

    collection.Dispose();
    return devices;
}

I did not test it, but i think iterating over a List while adding into it could be the issue.

Alexus
  • 276
  • 1
  • 5
  • 22
0

SerialPort.GetPortNames() reads the comports on computer. Use following code to read the comports and fill combo box (dropdown).

private void refreshPortChoices()
{
    int selectedPortIndex = this.cbbPortName.SelectedIndex;
    this.cbbPortName.Items.Clear();
    this.cbbPortName.Items.AddRange(SerialPort.GetPortNames());
    if (selectedPortIndex < this.cbbPortName.Items.Count)
    {
        this.cbbPortName.SelectedIndex = selectedPortIndex;
    }
    if (this.cbbPortName.Items.Count == 0)
    {
        this.cbbPortName.Items.Add("none");
        this.btnConnection.Enabled = false;
    }
    else
    {
        this.btnConnection.Enabled = true;
    }
}
Kalyan
  • 1,395
  • 2
  • 13
  • 26