Search code examples
arraysdelphibase64binaryfiles

Base64 encoded String to binary file


I have a Base64 encoded String that contains PDF data. Using the EncdDecd unit I can decode the String to a Byte Array.

This is where I am having trouble: I tried saving the characters to a String but once it hits a zero value (ASCII = 0 or #0 or $00) the String no longer appends. Example:

uses
  EncdDecd;
var
  EncodedString : String;
  Report : String;
  Base64Bytes: TBytes; // contains the binary data
begin
  Base64Bytes := DecodeBase64(EncodedString);
  for I := 0 to Length(Base64Bytes) - 1 do
    begin
      Report := Report + Chr(Base64Bytes[I]);
    end;

Writing to a text file seems to work better but after renaming it to .PDF the file does not open correctly.

How can I write to a binary file in Delphi? Or even save the data to a stream? Basically I am just trying to take the encoded String and save it to a PDF/binary file, or display the PDF in Delphi.

I have looked around quite a bit and found a possible solution in Saving a Base64 string to disk as a binary using Delphi 2007 but is there another way?


Solution

  • This should do it:

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

    Note: I have only compiled this in my head.