I’m making an app that needs to safely remove USB Drives and SD cards.
When i execute my code,I can’t never get to lock the drive.
If i skipp the lock part,The drive gets dissabled but if i start transferring data to it and execute my code,a msg box pops up saying: USB Cannot copy to “FileName” Device not ready.
And also,when i execute the code the drive stays visible in the pc and can be accessed again without having to replug.
Is that normal?
Am i doing some thing wrong?
Am i missing something?
Here’s my code:
HANDLE File;
DWORD BytesReturned;
char DrivePath[MAX_PATH];
char FullPath[MAX_PATH] = "\\\\.\\";
PREVENT_MEDIA_REMOVAL Prevent;
Prevent.PreventMediaRemoval = FALSE;
m_DriveALetter.GetWindowTextA(DrivePath,sizeof(DrivePath));
strncat_s(FullPath,DrivePath,2);
File = CreateFile(FullPath,GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
DeviceIoControl(File,FSCTL_LOCK_VOLUME,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
if(BytesReturned != 0)
{
DeviceIoControl(File,FSCTL_DISMOUNT_VOLUME,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
DeviceIoControl(File,IOCTL_STORAGE_MEDIA_REMOVAL,&Prevent,sizeof(PREVENT_MEDIA_REMOVAL),NULL,NULL,&BytesReturned,NULL);
DeviceIoControl(File,FSCTL_UNLOCK_VOLUME,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
MessageBox("You can now remove the USB Drive","Removed",MB_OK);
}
else if (BytesReturned == 0)
{
MessageBox("The Drive Could Not be Removed,Is being used by an app or has not finished an operation","Note",MB_OK);
}
CloseHandle(File);