Using Delphi 7 to develop our main application. We are importing files of data. The filesize in bytes exceeds the size of the integer variable that vcl and my code use to hold it...so it goes negative and empty file actions are taken...
Our current code to check the filesize (and thereby decide if empty) is:
function getfilesize(vfilename: string): integer;
var
SearchRec: TSearchRec;
beg开发者_开发问答in
try
result:= -1;
if FindFirst(vfilename, faAnyFile, SearchRec) = 0 then
result:= SearchRec.Size;
FindClose(SearchRec);
except
on e: exception do
raise exception.create('Error: functions\getfilesize - Unable to analyze file Attributes to determine filesize. '#13#10+e.message);
end;
Over the years this has changed back and forth, but for the last 5 years this has worked well.
the searchrec.size is an INTEGER so just changing our return type will not be sufficient. There are many other factors in store, related to our code and the database fields we use.
Q: What other D7 methods of determining the filesize in bytes will work for us, which use a larger datatype?
Q: Do you know of any other replacement functions to getFilesize in a larger integer?
GetFileAttributesEx()
is the most convenient Windows API to call. It's the fastest and unlike GetFileSize()
does not require you to obtain a file handle.
Wrap it up like so:
function FileSize(const FileName: string): Int64; overload;
var
AttributeData: TWin32FileAttributeData;
begin
if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @AttributeData) then
RaiseLastOSError;
Int64Rec(Result).Lo := AttributeData.nFileSizeLow;
Int64Rec(Result).Hi := AttributeData.nFileSizeHigh;
end;
If you happen to have a file handle then GetFileSizeEx()
is probably best:
function GetFileSizeEx(hFile: THandle; var FileSize: Int64): BOOL; stdcall; external kernel32;
function FileSize(hFile: THandle): Int64; overload;
begin
if not GetFileSizeEx(hFile, Result) then
RaiseLastOSError;
end;
try using the FindData.nFileSizeHigh
and FindData.nFileSizeLow
, you can write something like this :
function GetFileSizeExt(const FileName : TFileName) : Int64;
var
SearchRec : TSearchRec;
begin
if FindFirst(FileName, faAnyFile, SearchRec ) = 0 then
result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + Int64(SearchRec.FindData.nFileSizeLow)
else
result := -1;
FindClose(SearchRec) ;
end;
精彩评论