Detecting disk insertion and removal in the Compact Framework

I blogged about this feature of the SDF two years ago (almost to the day in fact), but it certainly bears repeating since it’s so useful.  If you need to know wehn a disk (SD, CF, USB, etc) has been attached or removed from a CE device (including Windows Mobile) you can use the SDF‘s DeviceStatusMonitor class (which, generally speaking, wraps the RequestDeviceNotifications API).  It’s really, really simple to use:


private void WatchForDrives()
{
  DeviceStatusMonitor monitor = new DeviceStatusMonitor(DeviceClass.FileSystem, false);
  monitor.StartStatusMonitoring();
  monitor.DeviceNotification += delegate(object sender, DeviceNotificationArgs e)
  {
    string message = string.Format(“Disk ‘{0}’ has been {1}.”, e.DeviceName, e.DeviceAttached ? “inserted” : “removed”);
    MessageBox.Show(message, “Disk Status”);
  };
}

3 Comments

  1. Does this also cover devices disappearing due to power loss as well? I remember having an issue _years_ back on a HHP 750 as the SD card would drop for a number of seconds if the device went into idle. This was a problem as some of the writes and flushes were delayed. So the proc was still working but the target disk was away.

  2. I’ve implemented this in order to detect when I connect/disconnect a usb cable from my mobile device, but i don’t get notifications of a disconnect until it is reconnected. In otherwords, I get dually notified (of both the "unmount" and "mount") when I re-attach a cable after detaching it.

    I am really just looking for the state as sending data to the port during when disconnected causes all future transmissions to fail. Any suggestions?

    Thanks,

    Ted

Leave a Reply