2

有人可以帮我解决这个问题:

{$IFDEF UNICODE}
function FormatStringByteSize( TheSize: Cardinal ): string;
{ Return a cardinal as a string formated similar to the statusbar of Explorer }
var
  Buff: string;
  Count: Integer;
begin
  Count := Length(Buff);
  FillChar(Buff, Count, 0);
  ShLwApi.StrFormatByteSize( TheSize, PWideChar(Buff), Length( Buff ) * SizeOf( WideChar ) );
  Result := Buff;
end;
{$ENDIF}
4

2 回答 2

1

你需要先设置buff的长度。(长度增益 = 0)

然后

  1. 将 TheSize 更改为 Int64 - 无论如何,大小 > 4GB 都需要它。
  2. 也许更改对 StrFormatByteSizeW 的调用(Delphi“标题”应该在 D2009+ 中完成此操作)
  3. 尽管有名称,FillChar 期望大小以字节为单位,而不是字符。不过这不会影响结果。
function FormatStringByteSize( TheSize: int64 ): string;
// Return an Int64 as a string formatted similar to the status bar of Explorer 
var
  Buff: string;
begin
  SetLength(Buff, 20);
  ShLwApi.StrFormatByteSizeW( TheSize, PWideChar(Buff), Length(Buff));
  Result := PChar(Buff);
end;

我目前无法在 D2009/10 中对此进行测试,因为尚未开始迁移到 Unicode(下一个项目!)它可以在带有 WideString 的 D2006 中使用。

于 2009-11-30T01:33:43.100 回答
1

至少在 Delphi 2009 中(无法在 2010 版中测试,因为我没有它)该StrFormatByteSize()函数是 Ansi 版本 ( StrFormatByteSizeA()) 的别名,而不是宽字符版本 ( StrFormatByteSizeW()) 的别名,因为它对于大多数其他 Windows API 函数。因此,您应该直接使用宽字符版本 - 也适用于早期的 Delphi 版本,以便能够处理大于 4 GB 的文件(系统)大小。

不需要中间缓冲区,您可以利用以下事实:StrFormatByteSizeW()将指向转换结果的指针返回为PWideChar

{$IFDEF UNICODE}
function FormatStringByteSize(ASize: int64): string;
{ Return a cardinal as a string formatted similar to the status bar of Explorer }
const
  BufLen = 20;
begin
  SetLength(Result, BufLen);
  Result := StrFormatByteSizeW(ASize, PChar(Result), BufLen);
end;
{$ENDIF}
于 2009-11-30T05:16:25.390 回答