How to remove USB drive using C#
Asked Answered
D

2

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.

Danielladanielle answered 28/7, 2009 at 15:13 Comment(0)
C
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!

Ceratoid answered 28/7, 2009 at 15:15 Comment(1)
The download in the linked article is no longer available, so this answer is no longer useful.Cline
C
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);
    }
}
Carbonado answered 15/2, 2021 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.