Jump to content

Recommended Posts

I create/open a TFileStream in non-exclusive mode with the following code:

 

if not FileExists(FileName) then //have to create it first and close it otherwise the share mode does not work!!
      begin
        Result := TFileStream.Create(FileName, fmCreate, fmShareExclusive);
        Result.free;
      end;

    Result := TFileStream.Create(FileName, fmOpenReadWrite, fmShareDenyNone);

By my reckoning I should be able to open  the file in read only mode:

 

fs := TFileStream.Create(FileName, fmOpenRead, fmShareDenyNone);

But it throws up an EFOpenError ie file in use by another process.

 

I have looked online and found old posts which suggest that the share modes do not function for fmCreate mode ie always created exclusively and that is why I create, then close and then open.

 

There was a post around 2010 which suggested the issue had been reported to Embarcadero and that it had been closed as fixed.

 

Couldnt find anything much later than this.

 

However as you can see , my problem is not with fmCreate, it is with fmOpenReadWrite. 

 

is there a bug with TFileStream or am I handling this in the wrong way?

 

If there is a bug, does anyone know a work around?

 

Share this post


Link to post
22 hours ago, Mark Williams said:

Result := TFileStream.Create(FileName, fmOpenReadWrite, fmShareDenyNone);

Sharing flags are used with the Mode parameter, not the Rights parameter.  Creation and Sharing flags can be OR'ed together in the Mode parameter, eg:

Result := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyNone{, 0});
Quote

I have looked online and found old posts which suggest that the share modes do not function for fmCreate mode ie always created exclusively and that is why I create, then close and then open.

That was true in the old days when fmCreate was defined as $FFFF and thus could not be mixed with any other flags, but that is no longer the case.  When the Rights parameter was introduced (which is not used on Windows when fmCreate is used), fmCreate was redefined as $FF00 so it can now be mixed with sharing flags, eg:

fs := TFileStream.Create(FileName, fmCreate or fmShareDenyNone{, 0});

If no sharing mode is specified, fmShareCompat is the default, except in the specific case of the old fmCreate value ($FFFF) being used, in which case the default is fmShareExclusive instead for backwards compatibility.

 

But either way, on Windows, fmShareCompat and fmShareExclusive mean the same thing - there is no sharing enabled on the file.

 

Edited by Remy Lebeau
  • Like 1
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×