5

I'm trying to write an application to remove USB Drives, but i can't find a way to do it. There's a .NET class to do this or it's possible using the Win32 API? All advises are welcome, thanks for the help.

doc
  • 269
  • 1
  • 4
  • 15

2 Answers2

6

Heres a link to what your looking for:

Eject USB disks using C#

Explains how to do it, and come with source code, enjoy!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
David Menard
  • 2,261
  • 3
  • 43
  • 67
  • 1
    The download in the linked article is no longer available, so this answer is no longer useful. – ygoe Jan 08 '16 at 22:29
1

I have test 2 variants, WMI and Shell and the Shell variant works as desired

Shell

/// <summary>
/// Eject USB Drice
/// STA Thread is required
/// </summary>
/// <remarks>
/// Install Shell32
/// 1. Right click project
/// 2. Click Add reference
/// 3. Click .COM tab in Add reference dialogue
/// 4. Select Microsoft Shell Controls and Automation
/// 5. Click OK
/// </remarks>
/// <param name="driveName">eg. D:</param>
private static void EjectDrive(string driveName)
{
    var staThread = new Thread(new ParameterizedThreadStart(EjectDriveShell));
    staThread.SetApartmentState(ApartmentState.STA);
    staThread.Start(driveName);
    staThread.Join();
}

private static void EjectDriveShell(object param)
{
    var driveName = param.ToString();

    var shell = new Shell();
    shell.NameSpace(17).ParseName(driveName).InvokeVerb("Eject");
}

WMI

You can use this script, see the documentation

private static void EjectDrice(string driveLetter)
{
    var scope = new ManagementScope(@"\\localhost\root\CIMV2", null);
    scope.Connect();
    var wql = $"SELECT * FROM Win32_Volume WHERE Name LIKE '{driveLetter}%'";
    var objectQuery = new ObjectQuery(wql);
    using var objectSearcher = new ManagementObjectSearcher(scope, objectQuery);
    foreach (ManagementObject classInstance in objectSearcher.Get())
    {
        using ManagementBaseObject inParams = classInstance.GetMethodParameters("Dismount");
        inParams["Force"] = false;
        inParams["Permanent"] = false;

        using ManagementBaseObject outParams = classInstance.InvokeMethod("Dismount", inParams, null);
    }
}
live2
  • 3,771
  • 2
  • 37
  • 46