Click here to Skip to main content
15,884,590 members
Articles / Desktop Programming / Windows Forms

Enumerate and Auto-Detect USB Drives

Rate me:
Please Sign up or sign in to vote.
4.83/5 (41 votes)
9 Mar 2010Ms-PL6 min read 236.6K   23.1K   136  
This article describes how to use the .NET System.Management WMI (Windows Management Instrumentation) wrappers to enumerate and describe USB disk drives. It also includes a non-Interop solution for detecting drive state changes as they come online or go offline.
//************************************************************************************************
// Copyright © 2010 Steven M. Cohn. All Rights Reserved.
//
//************************************************************************************************

namespace UsbManagerDemo
{
	using System;
	using System.Windows.Forms;
	using iTuner;


	public partial class MainForm : Form
	{
		private static readonly string CR = Environment.NewLine;
	
		private UsbManager manager;


		public MainForm ()
		{
			InitializeComponent();

			manager = new UsbManager();
			UsbDiskCollection disks = manager.GetAvailableDisks();

			textBox.AppendText(CR);
			textBox.AppendText("Available USB disks" + CR);

			foreach (UsbDisk disk in disks)
			{
				textBox.AppendText(disk.ToString() + CR);
			}

			textBox.AppendText(CR);

			manager.StateChanged += new UsbStateChangedEventHandler(DoStateChanged);
		}


		private void DoStateChanged (UsbStateChangedEventArgs e)
		{
			textBox.AppendText(e.State + " " + e.Disk.ToString() + CR);
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions