How to wait for a file to be created (Views: 100)


Does anyone have code that will wait for a file to be created? In particular I'm trying to come up with code that has pretty much a 0% processor usage.


The following function consumes very litte CPU while waiting for a file to be created:

function WaitForFile(FileName: string): Boolean;
{Wait for a file to be created. Tracks the directory were the file will be created.
Returns true if file exists, false on error.}
  WaitHandle: THandle;
  Result := False; {Let's assume we failed}
  WaitHandle := FindFirstChangeNotification(PChar(ExtractFilePath(FileName)),
  if (INVALID_HANDLE_VALUE = WaitHandle) then
    {The path to the file does not exists}
    if WaitForSingleObject(WaitHandle, INFINITE) = WAIT_OBJECT_0 then
    begin {Something happenned in the directory}
      if FileExists(FileName) then
        result := True;
        Break; {My file has been created, exit}
      {My file is not there, keep on}
      if not FindNextChangeNotification(WaitHandle) then
        {Something happened to the directory, maybe it was deleted}

<< Back to main page