在 Delphi 2010 或更高版本中获取文件的大小? [英] Getting size of a file in Delphi 2010 or later?

查看:14
本文介绍了在 Delphi 2010 或更高版本中获取文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Delphi 2010 在 IOUtils.pas 中有一组不错的新文件访问函数(我特别喜欢日期相关函数的 UTC 版本).到目前为止我想念的是

Delphi 2010 has a nice set of new file access functions in IOUtils.pas (I especially like the UTC versions of the date-related functions). What I miss so far is something like

TFile.GetSize (const Path : String)

Delphi 2010 获取文件大小的方法是什么?我是否必须返回并使用 FindFirst 来访问 TSearchRec.FindData?

What is the Delphi 2010-way to get the size of a file? Do I have to go back and use FindFirst to access TSearchRec.FindData?

谢谢.

推荐答案

我不确定是否有Delphi 2010"方式,但有一个 不涉及 FindFirst 和所有爵士乐的 Windows 方式.

I'm not sure if there's a "Delphi 2010" way, but there is a Windows way that doesn't involve FindFirst and all that jazz.

我将该例程的 Delphi 转换放在一起(并在此过程中对其进行了修改以处理 > 4GB 大小的文件,如果您需要的话).

I threw together this Delphi conversion of that routine (and in the process modified it to handle > 4GB size files, should you need that).

  uses
    WinApi.Windows;

  function FileSize(const aFilename: String): Int64;
  var
    info: TWin32FileAttributeData;
  begin
    result := -1;

    if NOT GetFileAttributesEx(PWideChar(aFileName), GetFileExInfoStandard, @info) then
      EXIT;

    result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32);
  end;

您实际上可以只使用 GetFileSize() 但这需要一个文件句柄,而不仅仅是文件名,并且类似于 GetCompressedFileSize() 建议,这需要两个要调用的变量.GetFileSize()GetCompressedFileSize() 都重载了它们的返回值,因此测试成功和确保有效结果只是有点尴尬.

You could actually just use GetFileSize() but this requires a file HANDLE, not just a file name, and similar to the GetCompressedFileSize() suggestion, this requires two variables to call. Both GetFileSize() and GetCompressedFileSize() overload their return value, so testing for success and ensuring a valid result is just that little bit more awkward.

GetFileSizeEx() 避免了处理 > 4GB 文件大小和检测有效结果的细节,但也需要文件 HANDLE,而不是名称,并且 (至少从 Delphi 2009 开始,我还没有检查 2010) 未在 VCL 中的任何地方为您声明,您必须提供自己的导入声明.

GetFileSizeEx() avoids the nitty gritty of handling > 4GB file sizes and detecting valid results, but also requires a file HANDLE, rather than a name, and (as of Delphi 2009 at least, I haven't checked 2010) isn't declared for you in the VCL anywhere, you would have to provide your own import declaration.

这篇关于在 Delphi 2010 或更高版本中获取文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆