How to make sure that a file was permanently saved on USB, when user doesn't use "Safely Remove Hardware"?

delphi, flush, usb, winapi, windows

Solution

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;

Problem

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?

Original source

Related problems