windows - 将文件大小转换为文本表示

标签 windows text formatting string-formatting windows-explorer

我正在构建在线文件管理器。它显示的列之一是文件大小,但这总是很大的字节数。我想像 Windows 资源管理器一样显示文件大小,使用较小的数字和适当的单位,例如5 MB 而不是 5000000

这对我来说一点也不难,但我想知道 Windows 是否有内置功能来执行此操作。已经有什么东西了,还是我必须自己动手?

最佳答案

我看到了 3 个变体:

function FormatFileSize(const ASize: UInt64; AKbMode: Boolean): UnicodeString;
var
  PS: IPropertySystem;
  PD: IPropertyDescription;
  PV: TPropVariant;
  Flags: DWORD;
  Display: PWideChar;
  PUI: IPropertyUI;
begin
  Result := '';

  // Variant 1
  if Succeeded(CoCreateInstance(CLSID_IPropertySystem, nil, CLSCTX_INPROC_SERVER, IPropertySystem, PS)) then
    begin
      if Succeeded(PS.GetPropertyDescription(PKEY_Size, IPropertyDescription, PD)) then
        begin
          PV.vt := VT_UI8;
          PV.uhVal.QuadPart := ASize;
          if AKbMode then Flags := PDFF_ALWAYSKB
                     else Flags := PDFF_DEFAULT;
          if Succeeded(PD.FormatForDisplay(PV, Flags, Display)) then
             begin
               Result := Display;
               CoTaskMemFree(Display);
             end;
          PD := nil;
        end;
      PS := nil;
    end;
  if Result <> '' then Exit;

  // Variant 2 - Windows XP mode, can be replaced with Variant 3
  if Succeeded(CoCreateInstance(CLSID_PropertiesUI, nil, CLSCTX_INPROC_SERVER, IPropertyUI, PUI)) then
    begin
      PV.vt := VT_UI8;
      PV.uhVal.QuadPart := ASize;
      SetLength(Result, 100);
      if Succeeded(PUI.FormatForDisplay(PKEY_Size.fmtid, PKEY_Size.pid, PV, PUIFFDF_DEFAULT, PWideChar(Result), Length(Result) + 1)) then
        Result := PWideChar(Result)
      else
        Result := '';
      PUI := nil;
    end;
  if Result <> '' then Exit;

  // Variant 3
  SetLength(Result, 100);
  if AKbMode then
    Result := StrFormatKBSizeW(ASize, PWideChar(Result), Length(Result))
  else
    Result := StrFormatByteSizeW(ASize, PWideChar(Result), Length(Result));
end;

关于windows - 将文件大小转换为文本表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48960032/

相关文章:

java - 格式化时 Eclipse 不会按行宽度分割字符串

mysql - 根据列值的变化向 MySQL 查询结果添加空白行

Java:无法将字符串转换为数组

Canvas 元素上的 HTML 文本字段

c++ - 我想重新运行一个线程

c++ - 未聚焦时 Direct2D 窗口呈黑色

regex - 如何使用正则表达式和 sed (或等效的 unix 命令行工具)来修复 LaTeX 标题中的标题大小写?

c# - String.Format 没有正确转换阿拉伯语的整数

Windows Workflow Foundation 4 (WF4) 重新托管

windows - 强制谷歌浏览器使用本地语音识别引擎