Rodrigo Farias Rezino
Rodrigo Farias Rezino

Reputation: 2799

How to read a file that is in use by other process?

I have an application that have a log system that create a file and keep it handle with a TFileStream, that is created with this way: FFileStream := TFileStream.Create(FFilename, fmOpenWrite);

Ok. When I try to open this file with notepad, no problem, with notepad++ no problem. When I try to load the file with other application that I created it raise my an error that says the file is in used by other process. I tried TStringList, LoadFromFile and TFileStream.Create(LFile, fmOpenRea);.

Some one knows how I can read this like the notepad and notepad++?

Tks.

Upvotes: 4

Views: 5245

Answers (3)

mg30rg
mg30rg

Reputation: 1359

I am using Delphi7 and I was experiencing, that TFileStream sometimes fail to open a file for reading, while it is only locked for writing. (Before one would start nagging about the sharing parameters of the TFileStream class; I know about them, and set them right.) While I was not yet able to find out the reasons of this clearly buggy behavior, I found that it can be worked around by using some other means of file handling:

While the file can not be opened with TFileStream - even with the right sharing settings (yes, I know what I am doing) - it could easily be opened using the appropriate WinAPI calls: CreateFile/ReadFile/SetFilePointer/CloseHandle wrapped in the Windows unit.

Upvotes: 1

Marjan Venema
Marjan Venema

Reputation: 19356

Erik got there first but uses fmShareDenyNone which would allow other processes to write to the same file. If you only want to allow reading by other processes, use:

FFileStream := TFileStream.Create(FFilename, fmOpenWrite or fmShareDenyWrite);

Upvotes: 7

Erik
Erik

Reputation: 91330

Use fmOpenWrite or fmShareDenyNone to enable sharing.

Upvotes: 4

Related Questions