Search code examples
windowsdelphiwinapifilehandle

Why do I get an "Invalid handle" error using GetFileSizeEx() with files marked read-only?


When I use the Windows API call GetFileSizeEx() from my Delphi 6 app on a read-only file, I get an O/S error code 6 ("Invalid file handle"). If I remove the read-only attribute from the file, the error disappears. Why am I getting that error and is there a way to use that call or a similar one with read-only files?

Here's the relevant code:

function GetFileSizeEx(hFile: THandle; var FileSize: Int64): BOOL; stdcall; external 'kernel32.dll' name 'GetFileSizeEx';

function easyGetFileSize(theFileHandle: THandle): Int64;
begin
    if not GetFileSizeEx(theFileHandle, Result) then
        RaiseLastOSError;
end;

-- roschler


Solution

  • Did you check the result of opening the file to get the file handle? Obviously if the file failed to open, you're calling GetFileSizeEx with an invalid handle. You'll need to open the file in a read-only mode.