2011-03-17 58 views
0

使用Delphi 7开发我们的主应用程序。我们正在导入数据文件。以字节为单位的文件大小超过了vcl和我的代码用来保存它的整数变量的大小...所以它变为负数并且空文件动作被采取...更改GetFileSize上的数据类型大小

我们当前的代码来检查文件大小决定是否为空)是:

function getfilesize(vfilename: string): integer; 
var 
    SearchRec: TSearchRec; 
begin 
    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; 

多年来这已来回改变,但在过去5年这 运作良好。

searchrec.size是一个INTEGER,所以只是改变我们的返回类型 是不够的。商店中还有很多其他因素,与我们的代码和我们使用的数据库字段有关。

问:对于我们来说,还有哪些其他D7确定字节文件大小的方法可以使用 ,它们使用更大的数据类型?

问:你知道任何其他替换函数getFilesize在一个更大的整数?

回答

7

GetFileAttributesEx()是最方便的Windows API调用。这是最快的,不像GetFileSize()不需要你获得文件句柄。

把它包起来,像这样:

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; 

如果你碰巧有一个文件句柄然后GetFileSizeEx()可能是最好的:

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;  
+0

+1这很好。有时候你有一个文件名,但不是一个句柄,其他时候你有一个句柄而不是文件名。 ;) – 2011-03-17 18:04:50

+0

@Craig当你有一个句柄它很简单,你可以调用['GetFileSizeEx()'](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx)。 – 2011-03-17 18:06:35

+0

'windows.GetFileAttributesEx'有什么不好? – 2011-03-17 18:38:56

2

尝试使用FindData.nFileSizeHighFindData.nFileSizeLow,你可以写这样的事情:

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; 
+0

+1较短的比我(现在我把它一起工作D7),但贵,因为你必须创建和销毁SearchRec。几乎可以肯定,你无关紧要。 – 2011-03-17 17:49:03