0

所以我一直在做一个项目,它将搜索驱动器,尝试识别特定的 USB 设备,如果找到它,将执行导出到该设备。完成此操作后,我会弹出一个对话框,通知已完成导出到设备,并询问用户是否希望弹出 USB 设备。

下面是处理 USB 设备的部分代码:

public class USBController
{
    const int OPEN_EXISTING = 3;
    const uint GENERIC_READ = 0x80000000;
    const uint GENERIC_WRITE = 0x40000000;
    const uint IOCTL_STORAGE_EJECT_MEDIA = 0x2D4808;

    [DllImport("kernel32", SetLastError = true)]
    private static extern int CloseHandle(IntPtr handle);

    [DllImport("kernel32", SetLastError = true)]
    private static extern int DeviceIoControl
        (IntPtr deviceHandle, uint ioControlCode,
          IntPtr inBuffer, int inBufferSize,
          IntPtr outBuffer, int outBufferSize,
          ref int bytesReturned, IntPtr overlapped);

    [DllImport("kernel32", SetLastError = true)]
    private static extern IntPtr CreateFile
        (string filename, uint desiredAccess,
          uint shareMode, IntPtr securityAttributes,
          int creationDisposition, int flagsAndAttributes,
          IntPtr templateFile);

    public static bool EjectDrive(char driveLetter, bool displayMessages)
    {
        string path = "\\\\.\\" + driveLetter + ":";

        IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0,
            IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);


        if ((long)handle == -1)
        {
            int error = Marshal.GetLastWin32Error();
            if (displayMessages)
                MessageBox.Show("Drive may still be in use. Unable to eject drive " + driveLetter + ":\\ \n\nError Code = " + error);

            return false;
        }

        int dummy = 0;

        DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0,
            IntPtr.Zero, 0, ref dummy, IntPtr.Zero);


        int returnValue = DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0,
            IntPtr.Zero, 0, ref dummy, IntPtr.Zero);

        if (returnValue == 0)
        {
            int error = Marshal.GetLastWin32Error();
            if (displayMessages)
                MessageBox.Show("DeviceIoControl encountered an error. \n\nError Code: " + error);

            return false;
        }


        CloseHandle(handle);
        if (displayMessages)
            MessageBox.Show("OK to remove drive.");

        return true;
    }
public static bool IsReady(char driveLetter)
    {
        DriveInfo[] drives = DriveInfo.GetDrives();

        foreach (DriveInfo drv in drives)
        {
            if (Convert.ToChar(drv.RootDirectory.ToString()[0]) == driveLetter && drv.IsReady)
            {
                return true;
            }
        }
        return false;
    }
}

所以一切正常,代码实际上会弹出一个 USB 设备。问题是导出的文件非常小,通常不到 100kb。文件似乎是在文件缓存系统中,因为写入文件后,我无法通过代码或windows提供的系统托盘中的工具弹出USB驱动器。它说设备仍然很忙。

有没有办法可以强制刷新缓存,或者另一种方法来解决这个问题?我的 IsReady 方法似乎更多地检查设备是否可以访问,不一定准备好弹出。

谢谢

4

0 回答 0