【问题标题】:How can I compare the size of a local file with a file on the web? [duplicate]如何将本地文件的大小与网络上的文件进行比较? [复制]
【发布时间】:2011-08-25 03:43:34
【问题描述】:

可能重复:
programatically get the file size from a remote file using delphi, before download it.

假设我有一个本地文件:

C:\file.txt

还有一个在网络上:

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

如何检查大小是否不同,如果不同则//做某事?

谢谢。

【问题讨论】:

标签: delphi delphi-7 delphi-xe


【解决方案1】:

要获取 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 位来表示文件大小是不够的,你需要对上面的两个函数做一些小的改动。

【讨论】:

  • 谢谢,正是我需要的。
  • +1 用于使用“标准”Windows 网络通话
  • 你的程序不错,谢谢分享。我打算问一个类似的问题,但搜索提出了这个问题。干得好:)
【解决方案2】:

您可以对文件发出 HTTP HEAD 请求并检查 Content-Length 标头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多