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?
views:
547answers:
3whatever happens, you can unplug the device yourself, i mean programatically. then you will be completely sure they have removed the device properly.
have a look at the answers for this question: safe-remove-usb-drive-using-win32-api. especially this link to a msdn kb article given in the answer.
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()
Here's a function I used to flush data to a USB drive before ejecting it programmatically. This clones functionality from Mark Russinovich's "Sync" utility. I've had no problems with this code and it has been running on a lot of systems for a couple of years.
The most relevant part of this code is the call to FlushFileBuffers.
function FlushToDisk(sDriveLetter: string): boolean;
var
hDrive: THandle;
S: string;
OSFlushed: boolean;
bResult: boolean;
begin
bResult := False;
S := '\\.\' + sDriveLetter + ':';
//NOTE: this may only work for the SYSTEM user
hDrive := CreateFile(PAnsiChar(S), GENERIC_READ or
GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
OPEN_EXISTING, 0, 0);
OSFlushed := FlushFileBuffers(hDrive);
CloseHandle(hDrive);
if OSFlushed then
begin
bResult := True;
end;
Result := bResult;
end;