Jens
Jens

Reputation: 357

Delphi - open a zipfile read-only

I use the internal TZipFile. When I open the zip then Delphi seems to open it exclusively. As long as the zipfile isn't freed the file access is denied

lZipFile := tZipFile.Create;
if lZipFile.IsValid( sPath) then begin
  lZipFile.Open( sPath, zmRead );
...
// access denied to sPath
end;
lZipFile.Free;

I only want to read. Why delphi is behaving that way? If I want to access a zip-file several times then I have to make a local copy and work with that copy? I don't really like this workaround. First of all since the zipfile could be huge.

Any idea what I can do to access the same zip in a read-only mode at the same time more than once?

Upvotes: 4

Views: 1219

Answers (1)

Uwe Raabe
Uwe Raabe

Reputation: 47769

You can create a TFileStream instance opened with the desired share mode. Then use the overloaded Open method of TZipFile that accepts a TStream.

Be aware that TZipFile.IsValid will try to open the file exclusive, too. As IsValid does nothing what Open also does, I added a try-except block to catch any invalid or unaccessible target. The call to IsValid can thus be omitted.

  zip := TZipFile.Create;
  try
    stream := TFileStream.Create(sPath, fmOpenRead + fmShareDenyWrite);
    try
      try
        zip.Open(stream, zmRead);
      except
        on EZipException do begin
          // access denied to sPath
        end;
      end;
    finally
      stream.Free;
    end;
  finally
    zip.Free;
  end;

Upvotes: 5

Related Questions