How to programmatically eject a removable disk (such as a flash card)

I need to be sure that after copying files to a flash card, the card buffer is actually shuffled to allow for safe removal of the flash card (the usual 'eject' option in Windows Explorer). I understand that there is a DeviceIoControl command. Is there anyone who already developed and tested such code?

SUMMARY
Win32 applications that run on Windows NT can programmatically eject media from drives that have hardware support for media removal. However, they must do so correctly to avoid corrupting the media. This article explains how to eject media correctly on Windows NT.
MORE INFORMATION
Windows NT version 4.0 and later support ejecting media formatted with NTFS and FAT file systems without shutting down the machine. Windows NT 3.51 and earlier support the ejecting FAT formatted media without shutting down. However, Windows NT versions 3.51 and earlier do not support removing media formatted with NTFS while the system is running. On these versions 3.51 and earlier the system must be shut down in order to avoid corrupting data on the media.
When a volume is mounted on Windows NT, there are two categories of read and write operations: 1) data operations performed by applications, and 2) file-system structure related operations performed by Windows NT. The second category is used by Windows NT to maintain the file system itself, such as directory entries of files (for example, file times, sizes, names, etc.).
Win32 applications can use either cached or uncached access to files. Windows NT, on the other hand, caches some write operations to file-system data structures to implement a "lazy-writer" scheme. This allows Windows NT to defer some writes to disk until they are absolutely required. This way, only the latest changes need to be written to disk if the file system data is updated often.
Because Windows NT uses a lazy writer system to update file system data structures on media, the media will be corrupted if the media is ejected while the system is updating this information. To avoid this problem, Win32 applications must take the following steps to correctly eject removable media and prevent possible data corruption:
Call CreateFile with GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, and OPEN_EXISTING. The lpFileName parameter should be \\.\X: (where X is the real drive letter). All other parameters can be zero.
Lock the volume by issuing the FSCTL_LOCK_VOLUME IOCTL via DeviceIoControl. If any other application or the system is using the volume, this IOCTL fails. Once this function returns successfully, the application is guaranteed that the volume is not used by anything else in the system.
Dismount the volume by issuing the FSCTL_DISMOUNT_VOLUME IOCTL. This causes the file system to remove all knowledge of the volume and to discard any internal information that it keeps regarding the volume.
Make sure the media can be removed by issuing the IOCTL_STORAGE_MEDIA_REMOVAL IOCTL. Set the PreventMediaRemoval member of the PREVENT_MEDIA_REMOVAL structure to FALSE before calling this IOCTL. This stops the device from preventing the removal of the media.
Eject the media with the IOCTL_STORAGE_EJECT_MEDIA IOCTL. If the device doesn't allow automatic ejection, then IOCTL_STORAGE_EJECT_MEDIA can be skipped and the user can be instructed to remove the media.
Close the volume handle obtained in the first step or issue the FSCTL_UNLOCK_VOLUME IOCTL. This allows the drive to be used by other processes.
The following code demonstrates how to accomplish safe ejection using the steps described above:
#include
#include
#include
#include
// Prototypes
BOOL EjectVolume(TCHAR cDriveLetter);
HANDLE OpenVolume(TCHAR cDriveLetter);
BOOL LockVolume(HANDLE hVolume);
BOOL DismountVolume(HANDLE hVolume);
BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPrevent);
BOOL AutoEjectVolume(HANDLE hVolume);
BOOL CloseVolume(HANDLE hVolume);
LPTSTR szVolumeFormat = TEXT("\\\\.\\%c:");
LPTSTR szRootFormat = TEXT("%c:\\");
LPTSTR szErrorFormat = TEXT("Error %d: %s\n");
void ReportError(LPTSTR szMsg)
_tprintf(szErrorFormat, GetLastError(), szMsg);
HANDLE OpenVolume(TCHAR cDriveLetter)
HANDLE hVolume;
UINT uDriveType;
TCHAR szVolumeName[8];
TCHAR szRootName[5];
DWORD dwAccessFlags;
wsprintf(szRootName, szRootFormat, cDriveLetter);
uDriveType = GetDriveType(szRootName);
switch(uDriveType) {
case DRIVE_REMOVABLE:
dwAccessFlags = GENERIC_READ | GENERIC_WRITE;
break;
case DRIVE_CDROM:
dwAccessFlags = GENERIC_READ;
break;
default:
_tprintf(TEXT("Cannot eject. Drive type is incorrect.\n"));
return INVALID_HANDLE_VALUE;
wsprintf(szVolumeName, szVolumeFormat, cDriveLetter);
hVolume = CreateFile( szVolumeName,
dwAccessFlags,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL );
if (hVolume == INVALID_HANDLE_VALUE)
ReportError(TEXT("CreateFile"));
return hVolume;
BOOL CloseVolume(HANDLE hVolume)
return CloseHandle(hVolume);
#define LOCK_TIMEOUT 10000 // 10 Seconds
#define LOCK_RETRIES 20
BOOL LockVolume(HANDLE hVolume)
DWORD dwBytesReturned;
DWORD dwSleepAmount;
int nTryCount;
dwSleepAmount = LOCK_TIMEOUT / LOCK_RETRIES;
// Do this in a loop until a timeout period has expired
for (nTryCount = 0; nTryCount < LOCK_RETRIES; nTryCount++) {
if (DeviceIoControl(hVolume,
FSCTL_LOCK_VOLUME,
NULL, 0,
NULL, 0,
&dwBytesReturned,
NULL))
return TRUE;
Sleep(dwSleepAmount);
return FALSE;
BOOL DismountVolume(HANDLE hVolume)
DWORD dwBytesReturned;
return DeviceIoControl( hVolume,
FSCTL_DISMOUNT_VOLUME,
NULL, 0,
NULL, 0,
&dwBytesReturned,
NULL);
BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPreventRemoval)
DWORD dwBytesReturned;
PREVENT_MEDIA_REMOVAL PMRBuffer;
PMRBuffer.PreventMediaRemoval = fPreventRemoval;
return DeviceIoControl( hVolume,
IOCTL_STORAGE_MEDIA_REMOVAL,
&PMRBuffer, sizeof(PREVENT_MEDIA_REMOVAL),
NULL, 0,
&dwBytesReturned,
NULL);
AutoEjectVolume(HANDLE hVolume)
DWORD dwBytesReturned;
return DeviceIoControl( hVolume,
IOCTL_STORAGE_EJECT_MEDIA,
NULL, 0,
NULL, 0,
&dwBytesReturned,
NULL);
BOOL EjectVolume(TCHAR cDriveLetter)
HANDLE hVolume;
BOOL fRemoveSafely = FALSE;
BOOL fAutoEject = FALSE;
// Open the volume.
hVolume = OpenVolume(cDriveLetter);
if (hVolume == INVALID_HANDLE_VALUE)
return FALSE;
// Lock and dismount the volume.
if (LockVolume(hVolume) && DismountVolume(hVolume)) {
fRemoveSafely = TRUE;
// Set prevent removal to false and eject the volume.
if (PreventRemovalOfVolume(hVolume, FALSE) &&
AutoEjectVolume(hVolume))
fAutoEject = TRUE;
// Close the volume so other processes can use the drive.
if (!CloseVolume(hVolume))
return FALSE;
if (fAutoEject)
printf("Media in Drive %c has been ejected safely.\n",
cDriveLetter);
else {
if (fRemoveSafely)
printf("Media in Drive %c can be safely removed.\n",
cDriveLetter);
return TRUE;
void Usage()
printf("Usage: Eject \n\n");
return ;
void main(int argc, char * argv[])
if (argc != 2) {
Usage();
return ;
if (!EjectVolume(argv[1][0]))
printf("Failure ejecting drive %c.\n", argv[1][0]);
return ;
REFERENCES
For more information on the IOCTLs and functions discussed in this article, please see the Win32 SDK Documentation.
For information about how to eject media on Windows 95, please use the following keywords to search the Microsoft Knowledge Base:
eject removable media

Similar Messages

  • How do you "eject" a camera or such device from the photos app after import?

    How do you "eject" a camera or such device from the photos app after import?

    Thanks for your answer. It certainly seemed that since there was no longer a control-click option in Photos for a mounted device that a hot dismount or eject would be OK. Should there be any caveats to the user who selected a Finder option not to show Hard disks, External discs or CDs DVDs and iPods--or is this still uniformly true across all devices (old iPads, Firewire, etc.)?
    This is only true for devices that are not accessible in the Finder. For iPhones, iPads, newer iPods. If a device shows up in Disk Utility as a mounted disk, you have to eject it properly.
    But the newer iOS devices are not mounted as a disk, that a user can write to or eject.
    For example, I just connected my iPhone 5s. It shows in Photos and iTunes in the sidebar, but Disk Utility does not show it as a mounted device, so there is no way to eject it.

  • How do I eject a dvd disk that will not eject when I highlight it and click the eject disk in finder, has anyone had this problem?

    How do I eject a dvd disk that will not eject after I have highlighted it and clicked the eject disk in finder file menu?

    Complements of Kappy:
    Try:
    1. Restart the computer and after the chime press and hold down the 
    left mouse button until the disc ejects.
    2. Press the Eject button on your keyboard.
    3. Click on the Eject button in the menubar.
    4. Press COMMAND-E.
    5. If none of the above work try this: Open the Terminal application in
    your Utilities folder. At the prompt enter or paste the following:
    /usr/bin/drutil eject
    If this fails then try this:
    Boot the computer into Single-user Mode. At the prompt enter the same command as used above. To restart the computer enter "reboot" at the prompt without quotes.

  • I have an iPad 2 and a Nikon DSLR. How can I transfer RAW/Tiff images using a compact flash card

    I have an iPad 2 and a Nikon DSLR. How can I transfer RAW/Tiff images using a compact flash card? Plugging in the camera at the ipad connector doesn't seem to work, possibly due to lack of power.

    This may apply.
    Fix (for Nikon D800)
    http://www.georgewheelhouse.com/blog/2012/10/ipad-ios-6-update---camera-connecti on-kit-fix
    Are you using an SD, SDHC, or SDXC card? And what capacity?
     Vheers, Tom

  • Hello everybody! i want ask you... how can i transfer my files from macbook pro to flash card or other devices?

    hello everybody! i want ask you... how can i transfer my files from macbook pro to flash card or other devices?

    Of course you can.  You may use USB drives, HDDs and other Mac if the need be.  More details from you will be required if you want more information.
    Ciao.

  • How do I eject the install disk on the mini mac?

    In wiping the mini mac, it keeps looping to the erase and install.  It won't allow me to shut down or eject the disk to put in the program disk.  When the screen gets to the Install Mac OS X, it won't show any disk (the Mac Mini) to install it.  I used the Utilities to erase and install, but I can't go any further.  It should install with a system lower than the OS X Yosemite.
    Message was edited by: llbixler

    Get help with the slot-loading SuperDrive on your Mac computer - Apple Support
    How force eject disc
    How do I eject a defective DVD?
    How to eject your disc?
    What model Mini?
    Some user have reported problems booting from a SL install DVD on a 2010 Mac Mini whose EFI was updated for Interent Recovery.

  • How can I eject a virtual disk that keeps coming back?

    For my MBP, with OS 10.6, I bought a WD eternal hard drive which comes with back-up software, "WD SmartWare." I use the Time Machine, and don't need other back-up software (I assume). A virtual disk holds the "SmartWare", and it shows on the desktop whenever the hard drive is connected.
    Here's the problem: If I try to eject the virtual disk and the partitions that I've put on the drive, and put my MBP to sleep to move to another location, the virtual disk icon immediately reappears - it will not stay ejected. If I simply pull out the USB of the drive, pick up MBP and go about my business elsewhere, when I return and reconnect the drive I get a warning that I've disconnected the drive incorrectly and could lose data, hence "don't do that!"
    So, so far the only way I can avoid the warning is to shut down the MBP and then disconnect the drive and leave. Then, the drive is happy.
    Question: is there a way to eject the virtual drive so that it stays ejected, so I can disconnect the WD hard drive to allow me a change of physical location using sleep mode and not shut-down for the Mac?
    Tomas

    if you use disk utility to delete all partitions on that drive and create a new partition and format it with mac os journalled your problem will be solved

  • How do i eject a stuck disk

    Having trouble booting my iMac, put Tech Tool Pro Disk in Drive, rebooted with C key, cannot boot.  restarted hold down the option key to get the recovery drive, but cannot get the TTPro disk to eject

    Restart holding the mouse button.
    If that doesn't work, see > How To Eject CD or DVD Stuck In Mac

  • Help, how Do I eject this miniature disk out of my iMac?

    I unknowingly place a miniature disk into my Mac trying to install a program. It didn't seem to take it in as well as a regular sized disk. It won't seem to eject, I can see a bit of it. I'm sort of convinced to use a small tool to try and fish it out, good idea? .-.
    What do you recommend?

    Same thing happened to me. I tried tweezers which didn't work and was about to go to Apple when I just tried to insert a normal cd. The normal cd seemed to push the mini DVD in and then the Imac spit it back out. I am not an Apple tech by any means and I dont want to mess up your computer, but it worked for me. Good luck.

  • How do you eject a cd stuck in your disk drive??

    how do you eject a cd stuck in your disk drive??

    Force eject a stuck cd/dvd
    First try the normal methods to remove the disc. Drag its icon to the Trash can in the Dock or select 'Eject' from the File menu.
    If you are running a virtual machine, e.g. VMFusion, ensure that the CD is disconnected from the virtual machine. This will sometimes allow the CD to now show up in Mac OS X.
    Shut down the computer and start up whilst holding down the mouse button. This may take some time, but keep your finger on the mouse button right up until the disc comes out or the log-in screen has appeared.
    If you have Toast Titanium installed on your computer, choose EJECT DISC from the menubar.
    Sometimes you can successfully use the eject disc button in iTunes even if the disc is not visible to the Finder
    Open Disc utility and choose the disc you wish to eject in the left-hand pane, then click on the Eject button.
    Some Macintoshes have a paperclip hole that you can insert a straightened paperclip into, manually triggering the eject mechanism.
    Open Terminal and type "drutil tray eject" to eject the disc/tray, and "drutil tray close" to close the tray.
    If your computer has an eject button on the keyboard, restart the computer holding down the Option key. When the startup disk selection screen appears, let go of the option key and press the keyboard's eject button.
    Source: http://guides.macrumors.com/Force_Eject_a_Stuck_CD_or_DVD

  • I used my snow leopard disk to erase my hard drive. Now I want to eject the snow leopard disk to clean install from the lion boot disk I made. How do I eject the snow leopard disk?

    I used my snow leopard disk to erase my hard drive. Now I want to eject the snow leopard disk to clean install from the lion boot disk I made. How do I eject the snow leopard disk? It is the start up disk and I can't figure out how to get it out of the computer so I can put my lion boot disk in. Thanks

    turn the mac all the way off. turn the mac on by pressing the power button. as soon as the apple logo appears, pres and hold your mouse button(trackpad mouse clicker etc...) until the CD comes out.

  • How do I eject a disk from my imac? force quit doesn, How do I eject a disk from my imac? force quit didn't work doesn

    How do I eject a disk from my Imac? I tried the manual button on the key board, and even tried force quit itunes....Help!

    A few suggestions here:
    http://osxdaily.com/2009/08/28/eject-a-stuck-disk-from-your-mac-dvd-super-drive/
    If all that fails, have a look at this video (do at your own risk!):
    http://www.youtube.com/watch?v=n7NYW9Dr448

  • Macbook Pro Model 5,4 Removable Disk Eject Problems.

    After the update to 10.6.8 the only way I am able to eject any removable drive is to open Disk Utility and hit eject in the action bar.  Even the option for ejecting is gone from the right click menu for all removable drives.  Also dragging the drive to the trash does nothing.

    Try downloading the Mac OS X 10.6.8 Update Combo. First do this:
    Repair the Hard Drive and Permissions
    Boot from your Snow Leopard Installer disc. After the installer loads select your language and click on the Continue button. When the menu bar appears select Disk Utility from the Utilities menu. After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported click on the Repair Permissions button. Wait until the operation completes, then quit DU and return to the installer.
    If DU reports errors it cannot fix, then you will need Disk Warrior and/or Tech Tool Pro to repair the drive. If you don't have either of them or if neither of them can fix the drive, then you will need to reformat the drive and reinstall OS X.
    Now reinstall with the combo updater.

  • How to access removable disks?

    I'm new on Elements and seem to stumble in the first round. I use  several extern datadisks (for photo's, audio etc.) via USB - how can I import photo's and other stuff from these? No other program but Elements has a problem with that...

    Thank you for your fast response!... From my side I should have supplied more info. My working horse  is an eMac with for all possible data (photos, audio, backup etc) extern (USB 2) drives attached. These drives are formatted with MacOS (journalled) or FAT32. The OS is Mavericks with Elements 12. When trying to import files - 'Photos from cameras or devices' - it says under 'Source' just 'No device found' whatever I try. However after several tries it now seems to work with Organizer. And so I take it from there...
    Op 30 apr. 2014, om 23:52 heeft A.T. Romano <[email protected]> het volgende geschreven:
    Re: How to access removable disks?
    created by A.T. Romano in Premiere Elements - View the full discussion
    HenkDeBoer
    What version of Premiere Elements are you using and what computer operating system is it running?
    For now, I will asssume Premiere Elements 12 on Windows 7, 8, or 8.1 64 bit.
    If you have video storage on an USB 2 or 3 external hard drive and you want to use any of it in a Premiere Elements project, you should be able to use Premiere Elements Add Media/Files and Folders to navigate to the external hard drive and import the file(s) into the project. What is happening in your case to give you problems?
    Is the external hard drive USB 2 or 3, is the drive letter staying constant, and is the external hard drive formatted NTFS if you are working on Windows? If Mac, what format is your external hard drive?
    Or do you have your media stored on a USB 2 or 3 Flash Drive or DVD disc...if so, then you would use Add Media/"Videos from Flip or Camera"/Video Importer after you insert your USB Flash Drive into a USB port or place the DVD disc in the burner tray.
    Please review and consider, supply details, and then we shall work on resolving whatever Premiere Elements workflow problems that you are having.
    Thanks.
    ATR
    Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/6345590#6345590
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/6345590#6345590
    To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/6345590#6345590. In the Actions box on the right, click the Stop Email Notifications link.
    Start a new discussion in Premiere Elements at Adobe Community
    For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • Do you know how to remove the removable disk dr

    i accidently pushed the removable disk so it used 28mb is there away to take that out

    What mp3 player do you have?
    In the Zen Micro it's Menu--> Extras-->Removable Disk--> and set how large you want it.
    If you don't want to use Removable Disk, set it to Disable and let it delete that partition.
    You will lose any data on it, so make sure you've backed it up if it's important to you.
    Other mp3 players probably use a similar system for Removable Disk.

Maybe you are looking for

  • How To Create Gallery Wizard in Jdev 10.1.3.1?

    Folks, I'm working on an extension that will add a new file extension to JDeveloper. I would my extension to show up in the File/New Gallery. I know that this will involve code in the extension.xml and one or more Java classes. I've looked at the PHP

  • Help Need - Urgent!!!!!!!!

    I have 2 DSO. say DSO1 (Header) and DSO2 (Item). DSO1 has ARRDT(date) and ARRTM(time) DSO2 has CRRDT(date) and CRRTM(time). I have created one more DSO3, which has these 4 fields and are mapped using 2 transformation to DSO1 and DSO2. Also I have a o

  • ICal data backup

    Is there any way to restore iCal data from iCloud if you haven't gone through the back up process? The last Calendar archive file on my desktop is from the day I started using iCloud in January.

  • How to set share folder for mac 8.6 in windows

    I know how to set share folder for mac 8.6 in windows xp. I installed the NetBIOS. But i still can not found windows share file in mac 8.6. Need to install 'DAVE'?

  • Could you help me for EBS

    HI, I have a question on EBS.We are using ff_5 for uploading bank statement.we do it in BAI format.It was alright till last week but when user is trying to upload for this week . we are getting an error of this kind.Could anyone help me. Its urgent.I