Categories
C#.NET Concept/algorithm Operating System

Refreshing USB ports using C#

Finished a project in which I need to refresh the USB ports by just before we start some particular benchmarking application my client has. Seems pretty easy job, if you know to gain access of system resource. But, it become fun job, when I found that knowledge of system is not even necessary for this job. Thanks to Microsoft’s `Devcon` utility, that already take care of it. So, in all what I have to do is just pass the correct parameter to it. The parameter is pretty easy, just pass the Hardware ID of USB port to refresh.

Yeah, that’s pretty easy. But …

Yes, but how we get the hardware id of USB port? Do we still need access to system resource for that? Well, it seems so. So we are back to square one. Well not really. I found a solution on web that points to `System.Management` namespace in .NET. What it does is it give you the list of all resources that are otherwise available through Computer management or such system resources. Here is main piece of code from article

public static List GetUSBDevices()
{
	List devices = new List();

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

	foreach (var device in collection)
	{
		devices.Add(new USBDeviceInfo(
		(string)device.GetPropertyValue("DeviceID"),
		(string)device.GetPropertyValue("PNPDeviceID"),
		(string)device.GetPropertyValue("Description"),
		device.ToString()
		));
	}

	collection.Dispose();
	return devices;
}

This provide the list of all USB port in system, and then you can pass the “DeviceID” to devcon and we are done.

For further clarification:

By Sumit Gupta

Sumit Gupta, born on 7th Feb 1981 in NCR, India. He lives a quiet life until he turn to a developer. Once he is in his professional life people start recognizing him for his work. Sumit Gupta is always keen to learn more and share his knowledge to anyone who deserve it. His goal of life is to code at least one 3D action game by itself or with his company Vikasumit [http://www.vikasumit.com].

2 replies on “Refreshing USB ports using C#”

Your question is rather unclear, DEVCON is command line, so you pass it as “parameter” to it. To find a DeviceID well there are few method, but I just query to Win32_Hub and it give me deviceID/hardwareID.

Comments are closed.