# VBForums CodeBank > CodeBank - Visual Basic .NET >  Detect when a USB mass storage device is plugged in.

## .NetNinja

If you need to detect when a USB Mass Storage Device is plugged in to the system use the below code. 

(I have to give some credit to obi1kenobi for tweaking this code)



```
Imports System.Management

Public Class Form3
    Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher
    Public USBDriveName As String
    Public USBDriveLetter As String

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        StartDetection()
    End Sub

    Private Sub Form3_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        m_MediaConnectWatcher.Stop()
        m_MediaConnectWatcher.Dispose()
    End Sub

    Public Sub StartDetection()
        Dim query2 As New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE TargetInstance ISA 'Win32_DiskDrive'")

        m_MediaConnectWatcher = New ManagementEventWatcher
        m_MediaConnectWatcher.Query = query2
        m_MediaConnectWatcher.Start()
    End Sub

    Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
        Dim mbo As ManagementBaseObject
        Dim obj As ManagementBaseObject

        mbo = CType(e.NewEvent, ManagementBaseObject)
        obj = CType(mbo("TargetInstance"), ManagementBaseObject)

        Select Case mbo.ClassPath.ClassName
            Case "__InstanceCreationEvent"
                If obj.Item("InterfaceType").ToString = "USB" Then
                    USBDriveName = obj.Item("Caption").ToString
                    USBDriveLetter = GetDriveLetterFromDisk(obj.Item("Name").ToString)
                    MessageBox.Show(USBDriveName & " (Drive letter " & USBDriveLetter & ") has been plugged in")
                End If
            Case "__InstanceDeletionEvent"
                If obj.Item("InterfaceType").ToString = "USB" Then
                    MessageBox.Show(USBDriveName & " was disconnected. " & USBDriveLetter & " is now inaccessible.") 'GetDriveLetterFromDisk(obj.Item("Name").ToString))
                    If obj.Item("Caption").ToString = USBDriveName Then
                        USBDriveLetter = ""
                        USBDriveName = ""
                    End If
                End If
            Case Else
                MessageBox.Show("nope: " & obj.Item("Caption").ToString)
        End Select
    End Sub

    Private Function GetDriveLetterFromDisk(ByVal Name As String) As String
        Dim oq_part, oq_disk As ObjectQuery
        Dim mos_part, mos_disk As ManagementObjectSearcher
        Dim obj_part, obj_disk As ManagementObject
        Dim ans As String = ""

        Name = Replace(Name, "\", "\\")

        oq_part = New ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=""" & Name & """} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
        mos_part = New ManagementObjectSearcher(oq_part)
        For Each obj_part In mos_part.Get()

            oq_disk = New ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=""" & obj_part.Item("DeviceID").ToString & """} WHERE AssocClass = Win32_LogicalDiskToPartition")
            mos_disk = New ManagementObjectSearcher(oq_disk)
            For Each obj_disk In mos_disk.Get()
                ans &= obj_disk.Item("Name").ToString & ","
            Next
        Next

        Return ans.Trim(","c)
    End Function
```

----------


## Biggy-D

```
Error	1	Type 'ManagementEventWatcher' is not defined.	
Error	2	Type 'WqlEventQuery' is not defined.	
Error	3	Type 'ManagementEventWatcher' is not defined.	
Error	4	Type 'System.Management.EventArrivedEventArgs' is not defined.	
Error	5	Type 'ManagementBaseObject' is not defined.	
Error	6	Type 'ManagementBaseObject' is not defined.	
Error	7	Type 'ManagementBaseObject' is not defined.	
Error	8	Type 'ManagementBaseObject' is not defined.	
Error	9	Type 'ObjectQuery' is not defined.	
Error	10	Type 'ManagementObjectSearcher' is not defined.	
Error	11	Type 'ManagementObject' is not defined.	
Error	12	Type 'ObjectQuery' is not defined.	
Error	13	Type 'ManagementObjectSearcher' is not defined.
```


What's Wrong !!??

----------


## MattP

Add a reference to System.Management (.NET tab).

----------


## Biggy-D

hmm !!!

thank you  MattP   :Smilie:

----------


## chris128

I made a very similar thing a while ago using APIs instead of WMI, if anyone finds that they cant use the WMI version .netninja has posted for some reason then maybe my old post could be useful: http://www.vbforums.com/showthread.php?t=534956
 :Smilie:

----------


## Biggy-D

how to show in a textbox the usb drive letter ??

----------


## .NetNinja

Look at the var USBDriveLetter....

It holds the Drive Letter.

----------


## obi1kenobi

Hey thanks for the credit!  :Big Grin:  Happy New Year!

----------


## obi1kenobi

@Biggy-D and everyone trying to use this class:
The events are raised on a thread different than the application's main (UI) thread. This means that if you want to modify any controls in the event handlers, you have to invoke the method on the UI thread instead of doing it directly. Not doing so will not result in an exception, however it will not produce the desired result.

If you need help with invoking the controls, this tutorial written by jmcilhinney will be more than able to instruct you in the ways of the Force  :Stick Out Tongue:

----------


## Chitranjan

Hey thanks for the code .

i have coded in new form But need your help as its not showing device attached to my pc.

how can i detect ANY  USB device plugged in?

----------


## WarrenW

Does this work for most any USB memory sticks? Or just something like a USB hard drive? I'm anxious to try it when I get home today!!

Thanks

----------


## chris128

> Does this work for most any USB memory sticks? Or just something like a USB hard drive? I'm anxious to try it when I get home today!!
> 
> Thanks


I know my code that uses Windows APIs rather than WMI (here: http://cjwdev.wordpress.com/2009/11/...-drive-letter/) works for any USB drive so I assume this method using WMI does as well  :Smilie:

----------


## WarrenW

Thanks for the info. I just looked at the codre on your site which I will give a try also. I think I remember reading somewhere that not all systems will support WMI or can have a problem. Not sure how true that is. But api calls should always work fine. Just curious, why are you looking for the test.txt file when connected? Is that just a test to show what you can do?

Thanks

----------


## chris128

> Thanks for the info. I just looked at the codre on your site which I will give a try also. I think I remember reading somewhere that not all systems will support WMI or can have a problem. Not sure how true that is. But api calls should always work fine.


Yep I prefer not to use WMI where ever possible because of precisely that reason. Admittedly WMI does work perfectly fine on the vast majority of machines but I've seen more than one case where it has not, so I use API's instead because they are pretty much guaranteed to work on any system.




> Just curious, why are you looking for the test.txt file when connected? Is that just a test to show what you can do?


Yeah exactly - I think when I originally wrote the code it was to help someone who wanted to detect a USB drive when it was plugged in and then check to see if a specific file existed on it (hence the need to know which drive letter it had been assigned)

----------


## WarrenW

Can this code or Chris's code be used in a Windows service? I tried creating one in VS2008 and putting the code in there but get alot of errors.

Thanks

----------


## chris128

> Can this code or Chris's code be used in a Windows service? I tried creating one in VS2008 and putting the code in there but get alot of errors.
> 
> Thanks


I know mine almost certainly cant because it relies on the message that Windows sends to all top level windows when a device is plugged in - and with a Service not having any windows (well, it should have anyway) that means it cannot receive the message.

----------


## WarrenW

Chris,

I put your code in a winform app in VS2008 and worked great!  Is there any way to detect when it is removed/unplugged from the computer? I'm sure it can detect changes but to determine the same drive was removed.

Thanks!

Warren

----------


## chris128

Yeah it can definitely detect the device being removed but not 100&#37; sure if you can get the drive letter that was removed - I imagine you can. I'll have a look tonight and see if I can put together an example.

----------


## Dananjaya

ThankX for the codes... It works grate..

----------


## sameer spitfire

Good Show Thanx

----------


## samar

HI Chris,
I am developing a window mobile application, and I want to check if USB is connected or not, I tried to paste your code but it has few errors while compiling, I am not sure if this not meant to use for mobile apps. This is my first mobile application, so I am not very much sure about this. Can you please advice, my requirement is simple that I need to check if device is connected or not.

Thanks
Samar

----------


## chris128

I've no idea about the WMI method that someone else mentioned but I would be surprised if the API method I provided works on mobile platforms

----------

