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.
How to remove USB drive using C#
Heres a link to what your looking for:
Explains how to do it, and come with source code, enjoy!
The download in the linked article is no longer available, so this answer is no longer useful. –
Cline
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);
}
}
© 2022 - 2024 — McMap. All rights reserved.