Home:ALL Converter>DeviceIoControl returns error 1 and 50 after using IOCTL_VOLUME_OFFLINE on a CD-ROM drive

DeviceIoControl returns error 1 and 50 after using IOCTL_VOLUME_OFFLINE on a CD-ROM drive

Ask Time:2018-12-14T19:32:55         Author:PezMutanT

Json Formatter

I would like to have my C++ Windows application to dismount a drive and not allowing the operative system to mount it back again automatically.

For this purpose, I use two functions: CreateFile for retrieving a handle to the drive and DeviceIoControl to perform different operations on that drive (via the handle retrieved from the first function).

After looking into Windows API documentation, my approach to do this is as follows:

  1. Calling CreateFile() to get a handle to the drive of the specified letter.
  2. Dismount the drive.
  3. Setting that drive as offline.
  4. Closing the handle of the drive.

The code looks like this (I omitted some variable declarations for simplicity):

HANDLE hVolume;
std::string volume_name = std::string("\\\\.\\D:");     //for drive with letter D
hVolume = CreateFile(
    volume_name.c_str(),
    GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL,
    OPEN_EXISTING,
    0,
    NULL);

DWORD dwBytesReturned;
DeviceIoControl(
    hVolume,
    FSCTL_DISMOUNT_VOLUME,
    NULL, 0,
    NULL, 0,
    &dwBytesReturned,
    NULL);

DeviceIoControl(
    hVolume,
    IOCTL_VOLUME_OFFLINE,
    NULL,
    0,
    NULL,
    0,
    &dwBytesReturned,
    NULL);

CloseHandle(hVolume);

Now, this works perfectly fine for several different USB drives I tried so far. They are dismounted correctly and they are not mounted back, not even if you double click on drive D showing on "My Computer" window.

When I tried on CD-ROM drives, things don't work anymore. Interestingly enough, I got two different errors, though (both when calling DeviceIoControl with IOCTL_VOLUME_OFFLINE parameter):

  1. On an internal CD-ROM drive (I'm doing these tests on a laptop), I got error 1 (ERROR_INVALID_FUNCTION).
  2. On two different external USB CD-ROM drives, I got error 50 (ERROR_NOT_SUPPORTED).

Has anyone worked with DeviceIoControl using IOCTL_VOLUME_OFFLINE and experienced this different behavior for USB drives and CD-ROM drives? Or does anyone know how to accomplish what I would like to do in some other way?

I'm using Windows 7, although, according to Windows documentation, this is available since Windows XP.

Any pointers will be appreciated. Thanks a lot.

Author:PezMutanT,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53778952/deviceiocontrol-returns-error-1-and-50-after-using-ioctl-volume-offline-on-a-cd
yy