Delphi – ShLwApi.StrFormatByteSize and Delphi 2010 Unicode

delphidelphi-2010unicode

Can someone help me fix this:

{$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}

Best Answer

At least in Delphi 2009 (can't test in version 2010 as I don't have it) the StrFormatByteSize() function is an alias to the Ansi version (StrFormatByteSizeA()), not to the wide char version (StrFormatByteSizeW()) as it is for most of the other Windows API functions. Therefore you should use the wide char version directly - also for earlier Delphi versions, to be able to work with file (system) sizes larger than 4 GB.

There's no need for an intermediate buffer, and you can make use of the fact that StrFormatByteSizeW() returns a pointer to the converted result as a 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}