When I save a file on a USB within my delphi application, how can I make sure the file is really (permanently) saved on the USB, when "Safely Remove Hardware" is not performed (especially forgotten to use)?
Telling our customer to use the windows feature "Safely Remove Hardware" doesn't work.
Is there a windows API command to flush the buffer, so that all data are written to the USB drive permanently?
If you remove your USB before cached information is written or while it is being written, chances are you'll end up with a corrupted file. Safely removing the USB clears the cache and the remaining data; stopping any process going on in the background.
If the drive isn't ejected correctly, that can lead to corrupt files, folders, and you'll probably have to end up reformatting the entire drive, which leads to all of your data being erased.
To avoid losing data, it's important to remove external hardware like hard drives and USB drives safely. Look for the Safely Remove Hardware icon on the taskbar.
When you click on the “safely remove hardware” option, you basically instruct the operating system to wait for all processes accessing a file system to finish, and then dismount the file system, which prevents any more read/write operations for the external drive.
When you open the file, specify "write through" (FILE_FLAG_WRITE_THROUGH flag to CreateFile()). This will force the OS to write out the file directly. It may still be in the OS cache to speed up subsequent reads, but that's not a problem for you.
If you do want to flush file buffers, there's of course always FlushFileBuffers()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With