Embarcadero: How to use TBase64Encoding's EncodeBytesToString method

3.9k views Asked by At

I am attempting to convert an array of bytes to a base64 encoded String using the EncodeBytesToString method of the TBase64Encoding class. The documentation for EncodeBytesToString states:

"Returns a string with the input array of bytes encoded up to the specified number of bytes."

Therefore, I attempted to encode my byte array like so:

TFile * File = new TFile();

TBytes Bytes = File->ReadAllBytes("D:\\Sample.pdf");

TBase64Encoding * Encoder = new TBase64Encoding();

String EncodedBytes = Encoder->EncodeBytesToString(Bytes, Bytes.Length);

However, I get the following error:

E2285 Could not find a match for 'TNetEncoding::EncodeBytesToString(TByteDynArray,int)'

I am confused, as the documentation seems to say that I should pass a TBytes object and an int into this function. What am I missing here?

2

There are 2 answers

0
luaphacim On BEST ANSWER

Try this:

//------------------------------------------------------------------------------
String __fastcall BytesToBase64( TByteDynArray _ArrayIn )
{
    TBase64Encoding * Encoding = new TBase64Encoding( 64, '\n' );
    String Result = Encoding->EncodeBytesToString( &_ArrayIn[0], _ArrayIn.High );
    delete Encoding;
    return Result;
}
//------------------------------------------------------------------------------
TByteDynArray __fastcall Base64ToBytes( String _64String )
{
    TByteDynArray My64Bytes = _64String.BytesOf();
    return TNetEncoding::Base64->Decode(&My64Bytes[0], My64Bytes.High);
}
//------------------------------------------------------------------------------
0
Martin Schneider On

System.NetEncoding.TNetEncoding provides the static property Base64 to retrieve an instance of TNetEncoding for base64 encoding.

So this will also work:

String __fastcall BytesToBase64(TByteDynArray _ArrayIn)
{
    return TNetEncoding::Base64->EncodeBytesToString(&_ArrayIn[0], _ArrayIn.High);
}