欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > C# 弹出USB移动存储设备【附源码】

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

2025/8/6 16:34:21 来源:https://blog.csdn.net/weixin_43880119/article/details/141713840  浏览:    关键词: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;}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词