There seem to be a few bugs in your sample code. If it was in fact copy & pasted from your program, then there would have to be something else going on.
First, you're calling a Unicode function with a MBCS string: the first argument should either be prepended with L
or surrounded with _T()
.
Second, and perhaps more importantly, "\\\\.\\E"
is not a valid name. You're missing a trailing colon: for opening a volume, it needs to be of the form \\.\X:
, or in your case "\\\\.\\E:"
.
After fixing those two bugs (the first preventing compilation, the second required to get anything other than INVALID_HANDLE_VALUE
back), everything seemed to be working as expected. I used GetProcessHandleCount to count the number of open handles, and it was the same before and after:
HANDLE m_driveHandle = NULL;
HANDLE m_process = GetCurrentProcess();
DWORD handleCount;
GetProcessHandleCount(m_process, &handleCount);
cout << "Currently held handles: " << handleCount << endl;
for (int i = 0; i < 10; ++i) {
m_driveHandle = CreateFileW(L"\\\\.\\E:",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (INVALID_HANDLE_VALUE == m_driveHandle) {
cout << "Invalid handle" << endl;
} else {
CloseHandle(m_driveHandle);
}
GetProcessHandleCount(m_process, &handleCount);
cout << "Currently held handles: " << handleCount << endl;
}
Commenting out the CloseHandle call causes handleCount to increment as expected, as well.