How to compare the size of a local file with a file on the Internet?

Possible duplicate:
programmatically obtain the file size from a remote file using delphi before downloading it.

Let's say I have a local file:

C: \ file.txt

And one on the Internet:

http://www.web.com/file.txt

How can I check if they are different, and if they are different, then // do something?

Thank.

+3
source share
2 answers

To get the file size 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 get the size of a local file, the easiest way is FindFirstFileto read it TSearchRec. However, a little elegant,

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.')

. 32 , .

+8

HTTP HEAD Content-Length.

+4

All Articles