C# + WMI + LPT help!

803 views Asked by At

I'm making an application that needs to list all the LPT ports in a machine with their IO addresses. (ie it's output : LPT1 [starting ; ending] ....)

Using WMI you can get this info.. the name/number from Win32_ParallelPort and the addresses from Win32_PortResource.

The problem is that i don't know how to associate the portname with it's addresses.

1

There are 1 answers

0
rene On

You have to query three times and loop over the results to get the matching records from ParallelPort, PnPAllocatedResource and PortResource. The following code does exactly that:

var parallelPort = new ManagementObjectSearcher("Select * From Win32_ParallelPort");
//Dump(parallelPort.Get());
foreach (var rec in parallelPort.Get())
{     
    var wql = "Select * From Win32_PnPAllocatedResource";
    var pnp = new ManagementObjectSearcher(wql);

    var searchTerm = rec.Properties["PNPDeviceId"].Value.ToString();
    // compensate for escaping
    searchTerm = searchTerm.Replace(@"\", @"\\");

    foreach (var pnpRec in pnp.Get())
    {
        var objRef = pnpRec.Properties["dependent"].Value.ToString();
        var antref = pnpRec.Properties["antecedent"].Value.ToString();  

        if (objRef.Contains(searchTerm))
        {
            var wqlPort = "Select * From Win32_PortResource";
            var port = new ManagementObjectSearcher(wqlPort);
            foreach (var portRec in port.Get())
            {
                if (portRec.ToString() == antref)
                { 
                    Console.WriteLine( "{0} [{1};{2}]",
                        rec.Properties["Name"].Value,
                        portRec.Properties["StartingAddress"].Value, 
                        portRec.Properties["EndingAddress"].Value );
                }
            }
        }
    }
}