C# 弹出USB外接硬盘(U盘)
原文: C# 弹出USB外接硬盘(U盘)

最近一个项目需要通过代码来弹出USB外接硬盘设备,经过google找到了下面这个类库:

http://www.codeproject.com/Articles/13530/Eject-USB-disks-using-C

不过这个类库只能在x86下使用,因此需要修改以下内容,使其适用于x64平台

修改DeviceClass为以下代码:

public List<Device> Devices{get{if (_devices == null){_devices = new List<Device>();int index = 0;while (true){Native.SP_DEVICE_INTERFACE_DATA interfaceData = new Native.SP_DEVICE_INTERFACE_DATA();interfaceData.cbSize = (UInt32)Marshal.SizeOf(interfaceData);if (!Native.SetupDiEnumDeviceInterfaces(_deviceInfoSet, IntPtr.Zero, ref _classGuid, (UInt32)index, ref interfaceData)){int error = Marshal.GetLastWin32Error();if (error != Native.ERROR_NO_MORE_ITEMS)throw new Win32Exception(error);break;}Native.SP_DEVINFO_DATA devData = new Native.SP_DEVINFO_DATA();IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(devData));Marshal.StructureToPtr(devData, p, true);UInt32 size = 0;if (!Native.SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref size, p)){int error = Marshal.GetLastWin32Error();if (error != Native.ERROR_INSUFFICIENT_BUFFER)throw new Win32Exception(error);}Native.SP_DEVICE_INTERFACE_DETAIL_DATA detailDataBuffer = new Native.SP_DEVICE_INTERFACE_DETAIL_DATA();if (IntPtr.Size == 8) // for 64 bit operating systems{detailDataBuffer.cbSize = 8;}else{detailDataBuffer.cbSize = 4 + Marshal.SystemDefaultCharSize; // for 32 bit systems}IntPtr pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(detailDataBuffer));Marshal.StructureToPtr(detailDataBuffer, pBuf, true);if (!Native.SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, ref interfaceData, pBuf, size, ref size, p)){int error = Marshal.GetLastWin32Error();if (error != Native.ERROR_INSUFFICIENT_BUFFER)throw new Win32Exception(error);}devData = (Native.SP_DEVINFO_DATA)Marshal.PtrToStructure(p, typeof(Native.SP_DEVINFO_DATA));Marshal.FreeHGlobal(p);detailDataBuffer = (Native.SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(pBuf, typeof(Native.SP_DEVICE_INTERFACE_DETAIL_DATA));Marshal.FreeHGlobal(pBuf);string devicePath = detailDataBuffer.DevicePath;Native.STORAGE_DEVICE_NUMBER storageDeviceNumber = GetDeviceNumber(devicePath);Device device = CreateDevice(this, devData, devicePath, storageDeviceNumber.DeviceNumber);_devices.Add(device);index++;}_devices.Sort();}return _devices;}}

  添加以下函数到DeviceClass.cs

internal Native.STORAGE_DEVICE_NUMBER GetDeviceNumber(string devicePath){IntPtr hFile = Native.CreateFile(devicePath.TrimEnd('\\'), 0, 0, IntPtr.Zero, Native.OPEN_EXISTING, 0, IntPtr.Zero);if (hFile.ToInt32() == Native.INVALID_HANDLE_VALUE)throw new Win32Exception(Marshal.GetLastWin32Error());int bytesReturned;Native.STORAGE_DEVICE_NUMBER storageDeviceNumber = new Native.STORAGE_DEVICE_NUMBER();int size = Marshal.SizeOf(storageDeviceNumber);IntPtr buffer = Marshal.AllocHGlobal(size);try{if (!Native.DeviceIoControl(hFile, Native.IOCTL_STORAGE_GET_DEVICE_NUMBER, IntPtr.Zero, 0, buffer, size, out bytesReturned, IntPtr.Zero)){// do nothing here on purpose}}finally{Native.CloseHandle(hFile);}if (bytesReturned > 0){storageDeviceNumber = (Native.STORAGE_DEVICE_NUMBER)Marshal.PtrToStructure(buffer, typeof(Native.STORAGE_DEVICE_NUMBER));}Marshal.FreeHGlobal(buffer);return storageDeviceNumber;}

  Native.cs 添加:

        [StructLayout(LayoutKind.Sequential)]internal struct STORAGE_DEVICE_NUMBER{public int DeviceType;public int DeviceNumber;public int PartitionNumber;}internal const int IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x2D1080;

  修改Volumn.cs

IntPtr hFile = Native.CreateFile(@"\\.\" + LogicalDrive, Native.GENERIC_READ, Native.FILE_SHARE_READ | Native.FILE_SHARE_WRITE, IntPtr.Zero, Native.OPEN_EXISTING, 0, IntPtr.Zero);

  为:

IntPtr hFile = Native.CreateFile(@"\\.\" + LogicalDrive, 0, Native.FILE_SHARE_READ | Native.FILE_SHARE_WRITE, IntPtr.Zero, Native.OPEN_EXISTING, 0, IntPtr.Zero);

  

修改Native.cs

     [StructLayout(LayoutKind.Sequential)]internal class SP_DEVINFO_DATA{internal int cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));internal Guid classGuid = Guid.Empty; // tempinternal int devInst = 0; // dumyinternal int reserved = 0;}[StructLayout(LayoutKind.Sequential, Pack = 2)]internal struct SP_DEVICE_INTERFACE_DETAIL_DATA{internal int cbSize;internal short devicePath;}[StructLayout(LayoutKind.Sequential)]internal class SP_DEVICE_INTERFACE_DATA{internal int cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));internal Guid interfaceClassGuid = Guid.Empty; // tempinternal int flags = 0;internal int reserved = 0;}

  为:

[StructLayout(LayoutKind.Sequential)]internal class SP_DEVINFO_DATA{internal int cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));internal Guid classGuid = Guid.Empty; // tempinternal int devInst = 0; // dumyinternal IntPtr reserved = IntPtr.Zero;}[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]internal struct SP_DEVICE_INTERFACE_DETAIL_DATA{internal Int32 cbSize;[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]internal string DevicePath;}[StructLayout(LayoutKind.Sequential)]internal struct SP_DEVICE_INTERFACE_DATA{internal UInt32 cbSize;internal Guid interfaceClassGuid;internal UInt32 flags;internal UIntPtr reserved;}

  修改Volume.cs

                                IntPtr extentPtr = new IntPtr(buffer.ToInt32() + Marshal.SizeOf(typeof(long)) + i * Marshal.SizeOf(typeof(Native.DISK_EXTENT)));

  为

                                IntPtr extentPtr = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(long)) + i * Marshal.SizeOf(typeof(Native.DISK_EXTENT)));

  

源代码下载

posted on 2019-06-29 16:50 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/11107083.html

C# 弹出USB外接硬盘(U盘)相关推荐

  1. 彻底解决电脑弹出USB设备时:提示该设备正在使用中无法弹出问题

    日常我们在使用移动硬盘或者U盘的时候,总是会遇到各种无法弹出的问题,如"该设备正在使用中.请关闭可能使用该设备的所有程序或窗口,然后重试."这种弹窗我们是否也经常遇到呢?那么今天我 ...

  2. 计算机老是跳出usb设备无法识别,如何解决电脑一直弹出USB设备无法识别的问题?...

    如何解决电脑一直弹出USB设备无法识别的问题? 我们在电脑上传输文件的时候都会使用到USB,但是有的时候会出现USB无法识别的情况,如果我们碰到这种问题应该如何操作呢?今天,小编就教大家解决电脑一直弹 ...

  3. 【完美解决】Windows下移动硬盘无法弹出 | 弹出USB大容量存储设备时出问题 | Windows无法停用设备 | \$Extend\$RmMetadata\$TxfLog\$TxfLog.blf

    前言 使用U盘或者移动硬盘弹总是会遇到无法弹出的情况.此时windows往往不会告诉你具体是什么设备占用,只会提示:弹出 USB 大容量存储设备 时出问题 或 Windows 无法停用"通用 ...

  4. 解决Win11(Win10同样适用)“弹出USB Attached SCSI(UAS)大容量存储设备时出问题”

    解决Win11"弹出USB Attached SCSI大容量存储设备时出问题" 一.问题描述 二.查找正在使用的程序的进程ID 三.删除进程AlibabaProtect.exe 一 ...

  5. 无法弹出usb设备、文件正在被占用

    问题 当我们弹出usb设备.删除文件时偶尔会出现如下问题,"该设备正在使用中"."操作无法完成,文件已被打开/正在使用"等 如图2所示的情况当然比较容易处理,因 ...

  6. 怎么查看usb读取信息_电脑弹出USB设备时提示该设备正在使用中的解决方法

    转载的文章,原文: 电脑弹出USB设备时提示该设备正在使用中的解决方法-系统城​www.xitongcheng.com 电脑弹出USB设备时提示该设备正在使用,虽然在正常显示时并没有程序在使用,但是确 ...

  7. 小米手机不弹出usb连接设置_安卓手机数据备份教程(华为、小米、oppo、vivo)...

    目前国产手机占比较高,而且各大手机产商非常人性化,提供数据备份功能,因此换机以及刷机都不会让人很犹豫.三星以及sony这种品牌明显水土不服,不建议使用. 目录: OPPO 华为 小米 vivo opp ...

  8. linux 弹出usb设备,linux安全移除USB设备

    使用图形界面时,一般只需要在相应的磁盘图标上点右键,选择"卸载"即可.如果卸载失败,请确保已没有程序访问该磁盘,再试一次. 只要卸载成功,这种方法就是安全的,因为缓冲内容会写入磁盘 ...

  9. 弹出USB大容量存储设备时出问题的解决方法

    转自:https://jingyan.baidu.com/article/5225f26bb92001e6fa0908d1.html 造成这个问题的原因:是有程序正在占用着U盘或者移动硬盘.有可能是输 ...

最新文章

  1. Linux_SquidProxyServer代理服务器
  2. 宿松长铺程集高中2021年高考成绩查询,2017宿松程集中学录取分数线(附2017高考成绩喜报)...
  3. 2019已过半,薪资相匹配除了实力,其实最重要的是……
  4. php 输入内容类型,实例解析php的数据类型
  5. 记一次 .NET 某资讯论坛 CPU爆高分析
  6. 医院设置(信息学奥赛一本通-T1338)
  7. [转载] 【Python-Numpy】numpy.random.randint用法
  8. kali安卓手机木马远控
  9. webstorm怎么汉化
  10. 【工作笔记001】SuperMap配准TransCAD底图
  11. 3D游戏引擎入门课程——场景渲染
  12. web前端----------网易云音乐播放器简单的实现(素材自行下载)
  13. 家里wifi网速越来越慢_家里WIFI出现卡顿,网速变慢怎么办?
  14. 大厂的安卓技术面试是酱紫的
  15. FPGA series # 基于SDx的fft函数加速
  16. 超适合新手练习的前端网页
  17. 955.WLB 不加班公司名单!再新增 5 家公司!
  18. TDD--01--ATDD、UTDD
  19. pip install psycopg2报错
  20. 使用TeXpad iOS实现移动办公(二)

热门文章

  1. 计算机网络 - 常见的网络协议
  2. 从代码级别的技术细节入手,看性能优化怎么做?
  3. 手撕SparkSQL五大JOIN的底层机制
  4. 掘金之旅APP开发:掘金之旅APP开发架构分析图以及部分开发源代码分享
  5. 比亚迪汽车的优势是什么
  6. linux top命令详解
  7. EM 管理 - 基础简介
  8. 静态优先权调度算法C语言实现6,静态优先权优先算法的进程调度程序文件.doc
  9. java爬虫爬b站_Java + golang 爬取B站up主粉丝数
  10. 物欲时代的终结 -《第 4 消费时代》