USB Dismount not turning off my USB Drive?

General discussion about C/C++

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

USB Dismount not turning off my USB Drive?

Postby AntiBNI » Mon Dec 08, 2008 4:18 pm

I'm making an app that needs to safely remove USB Drives and SD cards.

When i execute my code,the drive gets forced not to be ready.

I have an old 128MB usb drive and when 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?

Heres my code:

Code: Select all
HANDLE File;
    DWORD BytesReturned;
    char DrivePath[MAX_PATH] = "\\\\.\\J:";
    File = CreateFile(DrivePath,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);
    DeviceIoControl(File,FSCTL_DISMOUNT_VOLUME,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
    DeviceIoControl(File,IOCTL_STORAGE_MEDIA_REMOVAL,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
    DeviceIoControl(File,FSCTL_UNLOCK_VOLUME,NULL,NULL,NULL,NULL,&BytesReturned,NULL);
    CloseHandle(File);
        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);
        else
        MessageBox("You can now remove the USB Drive","Removed",MB_OK);


Is Disabling the drive while is being in a read/write process dangerous?

Help will be greatly appreciated.
AntiBNI
 
Posts: 1
Joined: Mon Dec 08, 2008 4:16 pm

Postby ventsyv » Sat Jan 03, 2009 5:21 pm

Disabling the drive while Read/Write operation is in progress will cause the operation to fail I think. So in that sense it is like pulling out the cable.

Your code appears fine to me. Try using a debugger and see where exactly the problem occurs. It sounds like the CreateFile call fails and you end up with invalid file handle.
Try adding some error checking:
Code: Select all
File = CreateFile(DrivePath,GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);
DWORD errMsg;
if (File == NULL)
{
   errMsg = GetLastError();
   cout<<"Error: "<<errMsg<<endl;
}
User avatar
ventsyv
 
Posts: 2810
Joined: Mon Sep 22, 2003 5:25 pm
Location: MD USA


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest