如何使用C#删除USB驱动器

时间:2009-07-28 15:13:26

标签: c# usb usb-drive

我正在尝试编写一个删除USB驱动器的应用程序,但我找不到办法。有一个.NET类来做这个或者可以使用Win32 API吗?欢迎提出所有建议,感谢您的帮助。

2 个答案:

答案 0 :(得分:7)

这是指向您所寻找的内容的链接:

Eject USB disks using C#

解释如何操作,并附带源代码,享受!

答案 1 :(得分:0)

我测试了 2 个变体,WMI 和 Shell,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

您可以使用此脚本,请参阅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);
    }
}