0

Possible Duplicate:
Looking for C# code for detecting removable drive (usb flash)

I'm woking in C# and WPF. My application has a custom dialog that displays all of the drives that are attached to the computer and allows the user to navigate to a particular folder, where a file will be output by the process in hand. I'm not using the common folder picker dialog because I need functionality not included in that common dialog, as well as a need to keep the dialog's appearance consistent with my application's style.

The purposee of the feature is to allow the user to export data to a thumb drive, so I'd like my appliation to receive notifications when a new drive becomes available. I'm using the string "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" to represent the MyComputer special folder internally.

I've tried passing this same string to an instance of the FileSystemWatcher class but this tells me that the string is not a valid path. So it looks like I can't achieve what I want this way.

What is the correct way to receive notification from the OS that a new thumb drive has been added to the computer and add it to my TreeView control?

Community
  • 1
  • 1
Tony Vitabile
  • 8,298
  • 15
  • 67
  • 123
  • Probably this question and its accepted answer will be a good start to resolve your problem http://stackoverflow.com/questions/412910/start-program-on-usb-hardware-plugin – Steve Jan 23 '13 at 17:02
  • [shameless self promotion] : http://www.dotnetthoughts.net/how-to-detect-usb-insertion-and-removal-in-vbnet/ – Anuraj Jan 23 '13 at 17:09

1 Answers1

2

I'm using the string "..." to represent the MyComputer special folder internally

This cannot work. It is indeed a special folder, it doesn't actually exist on the file system. These are virtual folders in Windows Explorer, implemented by a shell namespace extension. The presentation is convenient, it permits giving a consistent view of the "things are stored in a folder" paradigm. But without a real folder on the file system, FileSystemWatcher is incapable of generating change notifications.

Getting drive attachment notifications requires listening for plug-and-play events. Which typically starts with the WM_DEVICECHANGE message. You don't exactly want to have to write this code yourself, the setup api is quite gritty and the pinvoke is difficult. Nor do you have to, this has been wrapped many times before to make it easy to use in a C# program. Follow the links given in the comments on your question.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536