I'm trying to eject a USB drive in C# after I've copied some files to it.
However, after reading a lot of the examples of how to do that, I can't get anything to work for me.
[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);
How I'm calling it:
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
My drive letter is K
so it just puts that in the string and attempts to open the file (I'm not really sure about that), I'm hoping it will be the drive so that I can eject the USB thumbdrive.
Problem is that handle
is always -1
Am I formatting the path
string wrong? Or am I using the CreateFile
method incorrectly to get a handle to the drive I want to eject?
related:
Safely remove a USB drive using the Win32 API? (and related links)