user1580348
user1580348

Reputation: 6043

Convert TStream to String?

In Delphi 10.4, I try to convert a TStream to a string with this code:

function MyStreamToString(aStream: TStream): string;
var
  SS: TStringStream;
begin
  if aStream <> nil then
  begin
    SS := TStringStream.Create('');
    try
      SS.CopyFrom(aStream, 0); // Exception: TStream.Seek not implemented
      Result := SS.DataString;
    finally
      SS.Free;
    end;
  end else
  begin
    Result := '';
  end;
end;

But in this code line, I get an exception "TStream.Seek not implemented": SS.CopyFrom(aStream, 0);

Why? How can I "heal" this code?

Upvotes: 1

Views: 9236

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

The error means you are passing your function a TStream object that does not implement Seek() at all. Such as if you are passing in an actual TStream object and not a derived object, like TFileStream, TMemoryStream, etc, for instance:

var
  Strm: TStream;
begin
  Strm := TStream.Create; // <-- ERROR
  try
    MyStreamToString(Strm);
  finally
    Strm.Free;
  end;
end;

TStream is an abstract base class, it should never be instantiated directly.

In this case, the 32-bit Seek() method in the base TStream class calls the 64-bit Seek() method, but will raise that "Seek not implemented" exception if the 64-bit Seek() has not been overridden. A TStream-derived class must override either the 32-bit Seek() or the 64-bit Seek(), and the overridden method must not call the base TStream method it is overriding.

So, make sure you are passing in a valid stream object to your function.

Upvotes: 6

Related Questions