DeviceIoControl无法弹出非空的CDROM驱动器?

时间:2012-09-18 08:03:49

标签: c# winapi

我尝试使用DeviceIoControl函数(Win32 API函数)弹出我的CDROM驱动器,它在我的CDROM驱动器没有磁盘时工作正常,但在插入磁盘后,Marshal.GetLastWin32Error()返回32 (ERROR_SHARING_VIOLATION:进程无法访问该文件,因为它正由另一个进程使用),DeviceIoControl中传递的driveHandle由CreateFile()函数创建。

你可以帮帮我吗?我喜欢这种操作CD ROM相关内容的方式,我可以使用winmm.dll来弹出我的CDROM,但我认为这种方式值得尝试。

好的,这是代码:

using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;

using System.Runtime.InteropServices;

namespace DVD_ejector
{

    public partial class Form1 : Form
    {
        const int OPENEXISTING = 3;
        const int IOCTL_STORAGE_EJECT_MEDIA = 2967560;
        const uint GENERICREAD = 0x80000000;
        const int INVALID_HANDLE = -1;
        public Form1()
        {
            InitializeComponent();
            DriveInfo[] drs = DriveInfo.GetDrives();
            List<DriveInfo> cdRoms = new List<DriveInfo>();
            foreach (DriveInfo dInfo in drs)
            {                
                if (dInfo.DriveType == DriveType.CDRom)
                {
                    cdRoms.Add(dInfo);                    
                }                                
            }
            comboBox1.DataSource = cdRoms;               
            comboBox1.DisplayMember = "Name";

            if (comboBox1.Items.Count > 0) comboBox1.SelectedIndex = 0;
            button1.Click += (sender, e) =>
            {
                Eject(@"\\.\" + ((DriveInfo)comboBox1.SelectedItem).Name[0]+":");
            };
        }
        [DllImport("kernel32", SetLastError=true)]
        static extern IntPtr CreateFile(string fileName, uint desiredAccess, uint shareMode, IntPtr attributes,uint creationDisposition, uint flagsAndAttribute, IntPtr fileTemplate);
        [DllImport("kernel32")]
        static extern int CloseHandle(IntPtr fileHandle);
        [DllImport("kernel32")]
        static extern bool DeviceIoControl(IntPtr driveHandle, int ctrlCode, IntPtr inBuffer, int inBufferSize, IntPtr outBuffer, int outBufferSize, ref int bytesReturned, IntPtr overlapped);
        int bytesReturned;
        private void Eject(string cdDrive)
        {
            IntPtr driveHandle = CreateFile(cdDrive, GENERICREAD, 0, IntPtr.Zero, OPENEXISTING, 0, IntPtr.Zero);
            try
            {
                if((int)driveHandle != INVALID_HANDLE) 
                   DeviceIoControl(driveHandle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref bytesReturned, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                CloseHandle(driveHandle); 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

正如错误所述,设备正在被其他设备使用,但它在CreateFile调用而不是DeviceIoControl上失败,并且您的代码未正确检查失败。

您获得共享冲突的原因是因为您尝试以独占方式打开设备,如果ANYTHING尝试打开它或其上的文件(包括反病毒,资源管理器,搜索索引器等),则会失败。

此更新的Eject函数修复了共享模式和错误处理,现在可以在正确的位置报告错误。

private void Eject(string cdDrive) {
    IntPtr driveHandle = new IntPtr(INVALID_HANDLE);
    try {
        // Open the device
        driveHandle = CreateFile(cdDrive, GENERICREAD, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, IntPtr.Zero, OPENEXISTING, 0, IntPtr.Zero);
        if ((int)driveHandle == INVALID_HANDLE) { throw new Win32Exception(); }

        // Try and eject
        bool ejected = DeviceIoControl(driveHandle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref bytesReturned, IntPtr.Zero);
        if (!ejected) { throw new Win32Exception(); }

    } catch (Exception ex) {
        MessageBox.Show(ex.Message);

    } finally {
        if ((int)driveHandle != INVALID_HANDLE) { CloseHandle(driveHandle); }
    }
}