Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Sharing violation opening text file

I'm trying to open a text file for reading in a Delphi 7 app, but am getting I/O error 32 (sharing violation) because another application already has the file open. I've tried setting FileMode to "fmOpenRead or fmShareDenyNone" but now realise this doesn't apply to text files anyway.

Is there a way of reading text files that are open by another application?

var
  f: TextFile;
begin
  FileMode := fmOpenRead or fmShareDenyNone;   // FileMode IS NOT APPLICABLE TO TEXT FILES!!
  AssignFile(f, FileName);
  Reset(f);
like image 576
Simes Avatar asked Apr 26 '09 11:04

Simes


2 Answers

Use the LoadFromStream method of TStringList, rather than LoadFromFile. You get to control the locking that way:

var
    slFile: TStrings;
    stream: TStream;
begin
   slFile := TStringList.Create;
   try
      stream := TFileStream.Create(filename, fmOpenRead or fmShareDenyNone);
      try 
         slFile.LoadFromStream(stream);
      finally
         stream.Free;
      end;

      //Use the stringlist
   finally
      slFile.Free;
   end;
end;

That example is using the stream to load into a TStringList. If you only want to read pieces, you can do that. Just read from the stream.

like image 143
Ian Boyd Avatar answered Sep 19 '22 22:09

Ian Boyd


It depends on how that other process opened the file... If it opened the file exclusively you are not going to succeed at all.

And TextFile is old hat, I think it will open in exclusive mode to be compatible with Old style DOS. You should use TFileStream or similar.

TStringList may also work, again depending on what the other process is doing. But if the file is being written (like a .log file) the fmShareDenyWrite won't work.

like image 26
Henk Holterman Avatar answered Sep 18 '22 22:09

Henk Holterman