VB .NET USB Eject not working

Devon Nullman 40 Reputation points
2025-04-15T04:54:05.5333333+00:00

Form has a ComboBox and a button.

Imports System.IO

Imports System.Management

Imports Shell32

Public Class Form1

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown

'Dim driveArray() As String = System.IO.Directory.GetLogicalDrives

Dim Drives As DriveInfo() = System.IO.DriveInfo.GetDrives()

For Each d As DriveInfo In Drives

If d.DriveType = DriveType.Removable Then

CBDrives.Items.Add(d.Name)

End If

Next

End Sub

Private Sub Eject(DriveLetter As String)

Dim UsbDrive As String = DriveLetter

Dim ssfDRIVES As Integer = 17

Dim objShell As Object = CreateObject("shell.application")

objShell.NameSpace(ssfDRIVES).ParseName(UsbDrive).InvokeVerb("Eject") 'Exception = 'Object variable or With block variable not set

'powershell(this works)

'$driveEject = New-Object -comObject Shell.Application

'$driveEject.Namespace(17).ParseName("H:").InvokeVerb("Eject")

End Sub

Private Sub BtnEj_Click(sender As Object, e As EventArgs) Handles BtnEj.Click

Eject(CBDrives.Text)

End Sub

End Class

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,927 questions
{count} votes

Accepted answer
  1. Castorix31 89,136 Reputation points
    2025-04-23T14:46:49.1433333+00:00

    Casting ssfDRIVES works for me :

     objShell.NameSpace(CType(ssfDRIVES, Object)).ParseName(UsbDrive).InvokeVerb("Eject")
    
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.