【发布时间】:2011-08-25 03:43:34
【问题描述】:
可能重复:
programatically get the file size from a remote file using delphi, before download it.
假设我有一个本地文件:
C:\file.txt
还有一个在网络上:
如何检查大小是否不同,如果不同则//做某事?
谢谢。
【问题讨论】:
可能重复:
programatically get the file size from a remote file using delphi, before download it.
假设我有一个本地文件:
C:\file.txt
还有一个在网络上:
如何检查大小是否不同,如果不同则//做某事?
谢谢。
【问题讨论】:
要获取 Internet 上文件的文件大小,请执行以下操作
function WebFileSize(const UserAgent, URL: string): cardinal;
var
hInet, hURL: HINTERNET;
len: cardinal;
index: cardinal;
begin
result := cardinal(-1);
hInet := InternetOpen(PChar(UserAgent),
INTERNET_OPEN_TYPE_PRECONFIG,
nil,
nil,
0);
index := 0;
if hInet <> nil then
try
hURL := InternetOpenUrl(hInet, PChar(URL), nil, 0, 0, 0);
if hURL <> nil then
try
len := sizeof(result);
if not HttpQueryInfo(hURL,
HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,
@result,
len,
index) then
RaiseLastOSError;
finally
InternetCloseHandle(hURL);
end;
finally
InternetCloseHandle(hInet)
end;
end;
例如,你可以试试
ShowMessage(IntToStr(WebFileSize('Test Agent',
'http://privat.rejbrand.se/test.txt')));
要获取本地文件的大小,最简单的方法是FindFirstFile就可以了,读取TSearchRec。不过,稍微优雅一点的是
function GetFileSize(const FileName: string): cardinal;
var
f: HFILE;
begin
result := cardinal(-1);
f := CreateFile(PChar(FileName),
GENERIC_READ,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if f <> 0 then
try
result := Windows.GetFileSize(f, nil);
finally
CloseHandle(f);
end;
end;
现在你可以做
if GetFileSize('C:\Users\Andreas Rejbrand\Desktop\test.txt') =
WebFileSize('UA', 'http://privat.rejbrand.se/test.txt') then
ShowMessage('The two files have the same size.')
else
ShowMessage('The two files are not of the same size.')
注意:如果在你的情况下使用 32 位来表示文件大小是不够的,你需要对上面的两个函数做一些小的改动。
【讨论】:
您可以对文件发出 HTTP HEAD 请求并检查 Content-Length 标头。
【讨论】: