Robert Oschler
Robert Oschler

Reputation: 14375

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

Upvotes: 2

Views: 2213

Answers (2)

IceCold
IceCold

Reputation: 21194

Maybe something like this?

function GetFileSize_(CONST sFilename: string): Int64;   { NOT TESTED }
VAR aHandle: THandle;
begin
 aHandle:= CreateFile(PChar(sFilename), GENERIC_READ, FILE_SHARE_READ, NIL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

 if aHandle = INVALID_HANDLE_VALUE
 then Result:= -1
 else
  begin
   GetFileSizeEx(aHandle, Result);
   FileClose(aHandle);
  end;
end;

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308452

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.

Upvotes: 6

Related Questions