Mark Williams 14 Posted April 21, 2021 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
Remy Lebeau 1394 Posted April 21, 2021 (edited) 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 April 22, 2021 by Remy Lebeau 1 1 Share this post Link to post
Mark Williams 14 Posted April 22, 2021 Thanks. I didn't read the help file properly! Share this post Link to post