I want to check if a file exists and if exists whether it is empty or not.
I can handle file exists;
if FileExists(fileName) then
else
ShowMessage('File Not Exists');
How can I test for an empty file?
As @TLama suggested, following function returns true if the file is found and the size is zero.
function FileIsEmpty(const FileName: String): Boolean;
var
fad: TWin32FileAttributeData;
begin
Result := GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @fad) and
(fad.nFileSizeLow = 0) and (fad.nFileSizeHigh = 0);
end;
Test for a file size equal to zero. To see how to find the size of a file, refer to this question: Getting size of a file in Delphi 2010 or later?
var
sr: TSearchRec;
begin
if FindFirst('filename', faAnyFile, sr) = 0 then // If file exists ...
try
Result.size := sr.Size; // Check here is sr.Size = 0
Result.date := FileDateToDateTime(sr.Time);
finally
FindClose(sr);
end;
end;
Update: As more clear answer, there is complete function:
function FileExistsAndEmpty(const AFileName: string): Boolean;
var
sr: TSearchRec;
begin
Result := FindFirst(AFileName, faAnyFile, sr) = 0;
if Result then begin // file exists ...
Result := sr.Size = 0;
FindClose(sr);
end;
end;