How can I compare the size of a local file with a file on the web? [duplicate]
Possible Duplicate:
programatically get the file size from a remote file using de开发者_JAVA百科lphi, before download it.
Say I have a local file:
C:\file.txt
And one on the web:
http://www.web.com/file.txt
How can I check whether the size are different, and if they're different then //do something ?
Thanks.
To obtain the file size of a file on the Internet, do
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;
For example, you can try
ShowMessage(IntToStr(WebFileSize('Test Agent',
'http://privat.rejbrand.se/test.txt')));
To obtain the size of a local file, the simplest way is to FindFirstFile
on it and read the TSearchRec
. Slightly more elegant, though, is
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;
Now you can do
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.')
Notice: If in your case it is not enough to use 32 bits to represent the file sizes, you need to do some minor changes to the two functions above.
You can issue an HTTP HEAD request for the file and examine the Content-Length header.
精彩评论