Kermia
Kermia

Reputation: 4221

How to convert TBytes to Binary File? (using MemoryStream)

How can i convert Tbytes type to a Binary file using MemoryStream?

Upvotes: 15

Views: 18966

Answers (4)

Arioch 'The
Arioch 'The

Reputation: 16045

Well, if answers mention Delphi XE and other streams than TMemoryStream, then i suggest one more method.

 procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
 begin
   TFile.WriteAllBytes( FileName, Data );
 end;

Upvotes: 8

Mason Wheeler
Mason Wheeler

Reputation: 84540

Uwe's answer will work if you have TBytesStream available. If not:

procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
  stream: TMemoryStream;
begin
  stream := TMemoryStream.Create;
  try
    if length(data) > 0 then
      stream.WriteBuffer(data[0], length(data));
    stream.SaveToFile(FileName);
  finally
    stream.Free;
  end;
end;

Upvotes: 13

David Heffernan
David Heffernan

Reputation: 612884

Or directly with a TFileStream to cut down on the number of intermediate objects created:

procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
  Stream: TFileStream;
begin
  Stream := TFileStream.Create(FileName, fmCreate);
  try
    if Data <> nil then
      Stream.WriteBuffer(Data[0], Length(Data));
  finally
    Stream.Free;
  end;
end;

I don't believe using TMemoryStream is helpful here since it just involves an extra unnecessary heap allocation/deallocation.

Upvotes: 30

Uwe Raabe
Uwe Raabe

Reputation: 47704

F.I. in Delphi XE:

procedure SaveBytesToFile(const Data: TBytes; const FileName: string);
var
  stream: TBytesStream;
begin
  stream := TBytesStream.Create(Data);
  try
    stream.SaveToFile(FileName);
  finally
    stream.Free;
  end;
end;

Upvotes: 7

Related Questions