FileStream Create error in Delphi

Refresh I’ll share some tip on File Creation in Delphi. Some day I had to make a solution to create same file stream a lot times in a cycle and to show it at regular intervals (it was opened in another application). Well, if file is already created and time interval get’s too short, you might get an exception, that file is "in use on another process" and even setting file permissions doesn’t help:

   1: var File : TFileStream 

   2: File := TFileStream.Create(OutputFile, fmCreate or fmShareExclusive)

The solution is, first to check out if file is in use. We could use Windows API CreateFile function for this task:

   1: function IsFileInUse(FileName: TFileName): Boolean;

   2:   var HFileRes: HFILE;

   3: begin

   4:   Result := False;

   5:   if not FileExists(FileName) then Exit;

   6:   HFileRes := CreateFile( PChar(FileName), //Windows API Create

   7:     GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING,

   8:     FILE_ATTRIBUTE_NORMAL, 0);

   9:   Result := (HFileRes = INVALID_HANDLE_VALUE);

  10:   //returns false File handle if file is in use

  11:   if not Result then CloseHandle(HFileRes); //Deny and close handle

  12: end;

Then you can check if file is in use:

   1: if NOT IsFileInUse(OutputFile)

   2:    then File := TFileStream.Create(OutputFile, fmCreate or  fmShareExclusive);

update: Zarko Gajis from About.com made another universal function for checking if "FileIsInUse" here:

Programmatically Check If File is In Use – Delphi Code


2 Responses to “FileStream Create error in Delphi”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.