To use a TFileStream just to check if the file is in use, you need to use fmOpenRead instead of fmCreate, and you definitely need to use fmShareExclusive instead of fmShareDenyNone, and note that the file could fail to open for any number of reasons, not all of which are related to the file being in use, so you have to check for that, eg:
function FileReallyIsInUse(fName: string): boolean;
begin
Result := False;
try
TFileStream.Create(fName, fmOpenRead or fmShareExclusive).Free;
except
on E: EFOpenError do
Result := GetLastError() in [ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION];
end;
end;
However, the exception doesn't carry the error code, and using GetLastError() after the exception is raised does not guarantee the original error code is preserved. You are better off simply calling the Win32 CreateFile() function directly instead (which avoids the need to allocate an object in memory, or invoke the overhead of exception handling):
function FileReallyIsInUse(fName: string): boolean;
var
hFile: THandle;
begin
hFile := CreateFile(PChar(fName), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
CloseHandle(hFile);
Result := False;
end else
Result := GetLastError() in [ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION];
end;
Or, the RTL's FileOpen() function:
function FileReallyIsInUse(fName: string): boolean;
var
hFile: THandle;
begin
hFile := FileOpen(fName, fmOpenRead or fmShareExclusive);
if hFile <> INVALID_HANDLE_VALUE then
begin
FileClose(hFile);
Result := False;
end else
Result := GetLastError() in [ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION];
end;