External Storage Unit detection with C# in .NET (USB, Card Readers, etc)

It seems that the spanish written post for unit detection is pretty popular between my readers (and particularly Google), so I thought that time had come to upgrade it for a more international language.

This piece of code basically consists in a couple of methods that can enable any application to detect whenever a new storage device has been inserted into the computer, whether it is a CD/DVD, an USB key, a SD/MMC memory card, a external HDD… and to identify the newly inserted device unit’s name. This methods can be modified to fit the requirements of an existent application, or to build a new one that can use this functionality en new and creative ways (such as automated backups of the data on our USB Keys when inserting them and viceversa).

//It IS mandatory to include this reference
using System.Runtime.InteropServices;

//
//   You can add any code you want…
//   HERE …..
//

//Data structure that stores the connection management
[StructLayout(LayoutKind.Sequential)]
public struct DEV_BROADCAST_VOLUME
{
  public int dbcv_size;
  public int dbcv_devicetype;
  public int dbcv_reserved;
  public int dbcv_unitmask;
}

//Method to overwrite that manages the arrival of new storage units
protected override void WndProc(ref Message m)
{
  //This definitions are stored in “dbt.h” and “winuser.h”
  // There has been a change in the devices
  const int WM_DEVICECHANGE = 0×0219;
  // System detects a new device
  const int DBT_DEVICEARRIVAL = 0×8000;
  // Device removal request
  const int DBT_DEVICEQUERYREMOVE = 0×8001;
  // Device removal failed
  const int DBT_DEVICEQUERYREMOVEFAILED = 0×8002;
  // Device removal is pending
  const int DBT_DEVICEREMOVEPENDING = 0×8003;
  // The device has been succesfully removed from the system
  const int DBT_DEVICEREMOVECOMPLETE = 0×8004;
  // Logical Volume (A disk has been inserted, such a usb key or external HDD)
  const int DBT_DEVTYP_VOLUME = 0×00000002;
  switch (m.Msg)
  {
   //If system devices change…
   case WM_DEVICECHANGE:
    switch (m.WParam.ToInt32())
    {
     //If there is a new device…
     case DBT_DEVICEARRIVAL:
     {
      int devType = Marshal.ReadInt32(m.LParam, 4);
      //…and is a Logical Volume (A storage device)
      if (devType == DBT_DEVTYP_VOLUME)
      {
       DEV_BROADCAST_VOLUME vol;
       vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(
m.LParam, typeof(DEV_BROADCAST_VOLUME));
      MessageBox.Show(
        ”A storage device has been inserted, unit: ” +
        UnitName(vol.dbcv_unitmask));
      }
     }
    break;
    case DBT_DEVICEREMOVECOMPLETE:
     MessageBox.Show(”Device removed from system.”);
    break;
   }
   break;
  }
  //After the custom manager, we want to use the default system’s manager
  base.WndProc(ref m);
}

//Method to detect the unit name (”D:”, “F:”, etc)
char UnitName(int unitmask)
{
  char[] units ={ ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’,
    ’H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’,
    ’Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’ };
  int i = 0;
  //Convert the mask in an array, and search
  //the index for the first occurrenc (the unit’s name)
  System.Collections.BitArray ba = new
    System.Collections.BitArray(System.BitConverter.GetBytes(unitmask));
  foreach (bool var in ba)
  {
   if (var == true)
   break;
  i++;
  }
return units[i];
}

I’d be really pleased to know if this was useful 🙂

Publicado en C#. Etiquetas: , , , . 4 Comments »

4 respuestas to “External Storage Unit detection with C# in .NET (USB, Card Readers, etc)”

  1. nelson Says:

    Hi, I am student of El Salvador, I am working in a project with C#, I am looking for something that let me manage i/o
    is that posible with C#?

  2. Antonius Says:

    using System.IO; may be what you’re looking for. There are lots of documentation for all the classes there that are related with data streams, file management, etc.

  3. espinete Says:

    Where is the all full code source, please ??

    Thanks

    • Antonius Says:

      That’s all you need to detect USB devices. Just paste the code and modify the WndProc method (the part where it spawns a MessageBox) and place there the code you need for the actions you want performed when the software detects the arrival of the new device xD


Replica a nelson Cancelar la respuesta