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
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.
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;
精彩评论