最近一个项目需要通过代码来弹出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; // temp
internal int devInst = 0; // dumy
internal 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; // temp
internal 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; // temp
internal int devInst = 0; // dumy
internal 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)));

  

源代码下载

C# 弹出USB外接硬盘(U盘)的更多相关文章

  1. vc弹出USB的方法. 附试验通过的代码!

    vc弹出USB的方法. 附试验通过的代码! http://blog.sina.com.cn/s/blog_4fcd1ea30100qrzn.html (2011-04-15 10:09:48) boo ...

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

    我的计算机->管理->系统工具->事件查看器->自定义视图->Kernel-Pnp->详情->进程ID 然后在任务管理器里找到该进程(任务管理器->查看 ...

  3. WPF如何卸载U盘(弹出USB设备)

    应用程序和硬件设备的通信过程是:应用程序使用CreateFile函数打开设备,然后用DeviceIoControl()与硬件设备通信. CreateFile函数: [DllImport("k ...

  4. 【转】弹出USB大容量存储设备时出问题的解决方法

    原文链接 如下图所示,这个问题,相信很多人都有遇到过,而且经常难以解决,试了很多方法都无效.到最后,只能抱着侥幸的心理直接拔出,如果运气好,可能没有事,如果运气不好,你的U盘或者移动硬盘就要从此报废了 ...

  5. usb设备(移动硬盘或U盘),弹出时提示“有进程或程序占用,无法弹出”。解决办法

    测试环境:Win7(其他Windows系统环境,也可参考) 总结办法来源,https://bbs.csdn.net/topics/392297251?page=1文章中热心网友的评论指引 1. 控制面 ...

  6. USB设备的插入和弹出的监听以及软弹出可移动媒体(如Windows的移除USB设备) .

    一.监听USB设备的插入和弹出 当USB设备插入或者弹出时,Windows会产生一条全局消息:WM_DEVICECHANGE 我们需要做的是,获得这条消息的wParam参数,如果为DBT_DEVICE ...

  7. VMware 中如何打开U盘弹出U盘或者移动硬盘的(两种方法)

    1.U盘如下,插入后都是直接在win里面显示的 2.选择连接u盘 3.u盘就可以在虚拟机里面显示了 4.弹出则选择断开连接 扩展:如果无效:请参考这种方法 (给虚拟机分配一个临时硬盘,然后设置这个临时 ...

  8. 修改某个UITextField的键盘的返回键类型以及监听键盘的高度变化,取到键盘动画退出弹出的时间,一起随着键盘顶出来或者压下去,

    1.修改某个UITextField的键盘的返回键类型: [_bottomTextView setReturnKeyType:UIReturnKeyDone]; 1.1.textFied点击return ...

  9. (二十四)监听键盘的通知和键盘弹出隐藏的View移动

    让控制器监听键盘的通知,注意谁监听,谁的dealloc方法中就要remove,如果非ARC还要调用父类的dealloc方法. //监听键盘的操作: [[NSNotificationCenter def ...

随机推荐

  1. 得分(UVa1585)

    题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_prob ...

  2. Python全栈开发之4、内置函数、文件操作和递归

    转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5476760.html 一.内置函数 Python的内置函数有许多,下面的这张图全部列举出来了,然后我会把一些常用的拿 ...

  3. bzoj 1497 最小割

    思路:最小割好难想啊,根本想不到.. S -> 用户群 = c[ i ] 基站 -> T = p[ i ] 用户群 -> a[ i ] = inf 用户群 -> b[ i ] ...

  4. IntelliJ 、Pycharm、webstorm 2017 注册码及注册服务器

    jetbrains 家的东西都非常好看,但是价格贵的令人发指,所以我搭建了一个 Pycharm激活服务器,可以用来激活 Pycharm,IntelliJ IDEA,WebStorm.避免频繁更换激活码 ...

  5. JSP中的9大内置对象四大域与servlet里的三大域

    九大内置对象 隐式对象 说明 out 转译后对应JspWriter对象,其内部关联一个PringWriter对象 request 转译后对应HttpServletRequest/ServletRequ ...

  6. 密码嗅探工具dsniff

    密码嗅探工具dsniff   网络大量的服务都使用密码方式对使用者身份进行认证.如果使用非加密的方式传输,一旦数据被截获,就容易被嗅探到.Kali Linux预置了一款专用的密码嗅探工具dsniff. ...

  7. java 软引用,弱引用,强引用

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 强引用 ,有用的对象. 强引用 不会被回收. 软引用,有用 但不是必须的对象. 系统在发 ...

  8. BZOJ1016 JSOI2008最小生成树计数

    定理,在所有最小生成树中,相同边权的边出现的次数相同. 由于重复边权小于10条,可以跑2^10暴力 #include<bits/stdc++.h> using namespace std; ...

  9. [BZOJ4517][SDOI2016]排列计数(错位排列)

    4517: [Sdoi2016]排列计数 Time Limit: 60 Sec  Memory Limit: 128 MBSubmit: 1616  Solved: 985[Submit][Statu ...

  10. [BZOJ4890][TJOI2017]城市(DP)

    题目描述 从加里敦大学城市规划专业毕业的小明来到了一个地区城市规划局工作.这个地区一共有ri座城市,<-1条高速公路,保证了任意两运城市之间都可以通过高速公路相互可达,但是通过一条高速公路需要收 ...