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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With