Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 511
Kermia Avatar asked Jun 22 '11 18:06

Kermia


People also ask

What is the use of MemoryStream in c#?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

How do I save a memory stream?

Save MemoryStream to a String StreamWriter sw = new StreamWriter(memoryStream); sw. WriteLine("Your string to Memoery"); This string is currently saved in the StreamWriters buffer. Flushing the stream will force the string whose backing store is memory (MemoryStream).


4 Answers

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.

like image 163
David Heffernan Avatar answered Sep 28 '22 05:09

David Heffernan


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;
like image 40
Mason Wheeler Avatar answered Sep 28 '22 05:09

Mason Wheeler


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;
like image 29
Arioch 'The Avatar answered Sep 28 '22 06:09

Arioch 'The


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;
like image 27
Uwe Raabe Avatar answered Sep 28 '22 06:09

Uwe Raabe