Xwilarg
Xwilarg

Reputation: 424

How can I find the PID (Product ID) and VID (Vendor ID) of my devices in C#?

I'm trying to get the PID (Product ID) and VID (Vendor ID) of a device

I already found this post that ask the same question: How to get the VID and PID of all USB devices connected to my system in .net?
However I'm getting an exception in the ManagementClass constructor saying that it wouldn't find Win32_USBDevice

I found a suggestion of passing "Win32_DiskDrive" as a parameter instead but then it doesn't find anything and throw a NullReferenceException at the end of the scope (seems like it's related to IDiposable because adding "using" to the like make it throw there)

So my question is, how can I get the PID and VID of my devices using C# and .NET6?

Upvotes: 0

Views: 1584

Answers (1)

Marc Wittmann
Marc Wittmann

Reputation: 2671

Have you tried a WMI query? This should be pretty straightforward to get the device id

public class CustomWMIQuery
{
    public static void Main()
    {
        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                Console.WriteLine("Name: {0}", queryObj["Name"]);
                Console.WriteLine("Caption: {0}", queryObj["Caption"]);
                Console.WriteLine("Description: {0}", queryObj["Description"]);
                Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
                Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);
            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show("error: " + e.Message);
        }
    }
}

The device id looks somthing like this

  USB\VID_0911&PID_1240&MI_01\6&27AAD51C&0&0000

You can then take the information from VID_ to the next & seperator as the vendor Id You can then take the information from PID_ to the next & seperator as the product Id

Upvotes: 2

Related Questions