当前位置: 首页 > article >正文

C# 弹出USB移动存储设备【附源码】

using System;
using System.Management;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace USBEjectByGUIDApp
{
    class Program
    {
        // 定义常量
        const uint GENERIC_READ = 0x80000000;
        const uint GENERIC_WRITE = 0x40000000;
        const uint FILE_SHARE_READ = 0x00000001;
        const uint FILE_SHARE_WRITE = 0x00000002;
        const uint OPEN_EXISTING = 3;
        const uint IOCTL_STORAGE_EJECT_MEDIA = 0x2D4808;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr CreateFile(
            string lpFileName,
            uint dwDesiredAccess,
            uint dwShareMode,
            IntPtr lpSecurityAttributes,
            uint dwCreationDisposition,
            uint dwFlagsAndAttributes,
            IntPtr hTemplateFile);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool DeviceIoControl(
            IntPtr hDevice,
            uint dwIoControlCode,
            IntPtr lpInBuffer,
            uint nInBufferSize,
            IntPtr lpOutBuffer,
            uint nOutBufferSize,
            out uint lpBytesReturned,
            IntPtr lpOverlapped);

       public static void DisableUSBDrive(object uuid)
        {
            // 获取所有 USB 存储设备信息
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
            foreach (ManagementObject disk in searcher.Get())
            {

                string logicalDiskPath = GetLogicalDiskPathFromDiskDrive(disk);
                if (!string.IsNullOrEmpty(logicalDiskPath))
                {
                    string filename = @"\\.\\" + logicalDiskPath.Remove(2);
                    IntPtr handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                    if (handle != new IntPtr(-1))
                    {
                        uint byteReturned;
                        bool result = DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, out byteReturned, IntPtr.Zero);
                        CloseHandle(handle);
                    }
                }
            }
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr hObject);

        private static string GetLogicalDiskPathFromDiskDrive(ManagementObject disk)
        {
            ManagementObjectSearcher partitionSearcher = new ManagementObjectSearcher($"ASSOCIATORS OF {{Win32_DiskDrive.DeviceID='{disk["DeviceID"]}'}} WHERE AssocClass = Win32_DiskDriveToDiskPartition");
            foreach (ManagementObject partition in partitionSearcher.Get())
            {
                ManagementObjectSearcher logicalDiskSearcher = new ManagementObjectSearcher($"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{partition["DeviceID"]}'}} WHERE AssocClass = Win32_LogicalDiskToPartition");
                foreach (ManagementObject logicalDisk in logicalDiskSearcher.Get())
                {
                    return logicalDisk["DeviceID"].ToString();
                }
            }
            return null;
        }
    }
}

http://www.kler.cn/a/284382.html

相关文章:

  • 《Django 5 By Example》阅读笔记:p76-p104
  • 编写红绿起爆线指标(附带源码下载)
  • 前端垂直居中的多种实现方式及应用分析
  • 如何在算家云搭建Peach-9B-8k-Roleplay(文本生成)
  • 【嵌入式开发】单片机CAN配置详解
  • C++初阶——list
  • 假如我是前端面试官
  • 解决移动端使用Vant van-overlay 遮罩层导致的弹窗不可滚动问题
  • Linux 非root用户部署elasticsearch 7.17.23和ik分词器
  • cnocr 安装
  • 华为云征文|Flexus云服务器搭建基础环境
  • 聚合函数的艺术:SQL中的SUM、AVG、MAX、MIN深度解析
  • JavaScript在网页设计
  • LuaJit分析(六)luajit -bl 命令分析
  • OpenCV几何图像变换(11)极坐标转换函数warpPolar()的使用
  • 微服务事务管理
  • 计网_整体概念逻辑简单过一遍
  • 谷粒商城实战笔记-265~268-商城业务-订单服务-订单确认页模型抽取和数据填充-Feign丢失数据问题
  • ws2812b效果研究之一 cylon
  • linux------数据结构
  • Scriban:高效、强大的.NET开源模板引擎,可用于邮件、文档生成!
  • 数据结构—栈和队列
  • git 更改分支名称
  • 每日OJ_牛客_数据库连接池(简单模拟)
  • 迁移学习之领域自适应(domain adaptation)
  • 护网中经常使用的一些工具(非常详细)零基础入门到精通,收藏这一篇就够了