主窗口.CreateFile总是返回-1

本文关键字:返回 窗口 CreateFile | 更新日期: 2023-09-27 18:04:06

我试图在c#中弹出USB驱动器后,我已经复制了一些文件。

然而,在阅读了很多关于如何做到这一点的例子之后,我不能让任何东西为我工作。

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

如何命名:

string path = "''''.''" + driveLetter + ":";
IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, 
  IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
MessageBox.Show(GetLastError().ToString());//gives me zero

我的驱动器号是K,所以它只是把它放在字符串中,并试图打开文件(我不太确定),我希望它将是驱动器,这样我就可以弹出USB拇指驱动器。

问题是handle总是-1

我格式化path字符串错误吗?或者我是否错误地使用CreateFile方法来获取我想要弹出的驱动器的句柄?

相关:

通过c#弹出USB设备

使用Win32 API安全地移除USB驱动器?(及相关链接)

主窗口.CreateFile总是返回-1

在这里找到答案(通过c#弹出USB设备,参见Roger Deep的答案)

<标题>短答:
IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE, 
    FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, 0x3, 0, 
    IntPtr.Zero);

我不知道区别是什么,但它给了我正确的驱动器句柄,其余的代码现在工作!

长回答,我的完整代码删除USB驱动器(WPF窗口):

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    EjectDrive('K');
}
void EjectDrive(char driveLetter)
{
    string path = @"''.'" + driveLetter + @":";
    IntPtr handle = CreateFile(path, GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, 0x3, 0, IntPtr.Zero);
    if ((long)handle == -1)
    {
        MessageBox.Show("Unable to open drive " + driveLetter);
        return;
    }
    int dummy = 0;
    DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0,
        IntPtr.Zero, 0, ref dummy, IntPtr.Zero);
    CloseHandle(handle);
    MessageBox.Show("OK to remove drive.");
}
[DllImport("kernel32", SetLastError = true)]
private static extern IntPtr CreateFile
    (string filename, uint desiredAccess,
        uint shareMode, IntPtr securityAttributes,
        int creationDisposition, int flagsAndAttributes,
        IntPtr templateFile);
[DllImport("kernel32")]
private static extern int DeviceIoControl
    (IntPtr deviceHandle, uint ioControlCode,
        IntPtr inBuffer, int inBufferSize,
        IntPtr outBuffer, int outBufferSize,
        ref int bytesReturned, IntPtr overlapped);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);