In our project, we are using a StreamWriter to write into a log file.
While writing, I wanted to search inside the file for some specific lines. E.g. during a unit test. But somehow I can't read from the file, because it is blocked by a process. I don't understand why it is blocked, because I think I opened the FileStream without any blocking.
I extracted everything from to project into this little example. What do I have to change to not block the file for reading, while writing to it?
program Playground;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Classes;
var
FileStream: TFileStream;
FileStreamWriter : TStreamWriter;
strList: TStringList;
fileName: String;
begin
try
strList := TStringList.Create;
fileName := 'TestFile.txt';
FileStream := TFileStream.Create(fileName, fmCreate or fmShareDenyNone);
FileStreamWriter := TStreamWriter.Create(FileStream, TEncoding.Unicode);
FileStreamWriter.WriteLine('12345');
strList.LoadFromFile(fileName); // Crashes because a proccess blocks the file
strList.Free;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
question from:https://stackoverflow.com/questions/65843958/tstreamwriter-locks-file-for-read