GetFileSize Function

Declare Function GetFileSize Lib "kernel32.dll" (ByVal hFile As Long, lpFileSizeHigh As Long) As Long

Platforms: Win 32s, Win 95/98, Win NT

GetFileSize determines the size of the file. The file size is given in a 64-bit value that is split into two 32-bit values. The high-order half is put into the variable passed as lpFileSizeHigh; the low-order half is returned by the function. To get the size, you can either put the binary or hexadecimal values of the two variables side-by-side, or use the formula filesize = lpFileSizeHigh * 2^32 + return value. If an error occurs, the function instead returns -1.

hFile
A handle to the file to determine the size of. The file must be opened with at least either read-level or write-level access.
lpFileSizeHigh
Variable that receives the high-order half of the file size.

Example:

' Display the file size of "C:\MyProgram\datafile.txt".  Note how
' the alternate declare of the CreateFile function (needed to get the file's handle)
' must be used -- see that function's page for details.
Dim hfile As Long  ' receives a handle to the file
Dim loworder As Long, highorder As Long  ' receive the low- and high-order halves of the file size
Dim retval As Long  ' return value

' Get a handle to the file using CreateFile's alternate declare (necessary for non-Win NT).
hfile = CreateFileNS("C:\MyProgram\datafile.txt", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, 0)
If hfile = -1 Then  ' error opening the file
  Debug.Print "Could not open file C:\MyProgram\datafile.txt"
  End  ' abort the program
End If

' Read and display that file's size in bytes.
highorder = 0  ' initialize the value for high-order half
loworder = GetFileSize(hfile, highorder)  ' read the file's size
If highorder = 0 Then  ' if there is no high-order part
  Debug.Print "File size:"; loworder; "bytes"  ' display the file size
Else  ' if there is a high-order part (file size >= 4.29 GB!)
  ' Visual Basic has no 64-bit variables, so we can't display the actual value:
  Debug.Print "File size:"; highorder; "* 2^32 +"; loworder; "bytes (in base-10)"
  ' But we can combine the two hex values to give the result in hexadecimal:
  Debug.Print "File size: "; Hex(highorder); Hex(loworder); " bytes (in hexadecimal)"
End If

' Close the file
retval = CloseHandle(hfile)  ' close the handle

See Also: GetFileInformationByHandle
Category: Files

Go back to the alphabetical Function listing.
Go back to the Reference section index.


This page is copyright © 2000 Paul Kuliniewicz. Copyright Information.
Go back to the Windows API Guide home page.
E-mail: vbapi@vbapi.com Send Encrypted E-Mail
This page is at http://www.vbapi.com/ref/g/getfilesize.html