Convert pdf or any type of file to base 64 string in AX using x++

Here is a code snippet to convert any file into a base64 string in x++ using some dot net inbuilt classes in AX.

To convert it, initially clrinterop permission must be granted to access the dot net inbuilt classes then load the file into file info, initialize the byte array with the length of file, stream and read the file and then convert the file to a base 64 string.

System.Byte[] pdfDocBuffer;
System.IO.FileInfo fi_pdfDoc;
System.IO.FileStream fs;
str Content;
// Grant clrinterop permission.
new InteropPermission(InteropKind::ClrInterop).assert();
//Load the file
fi_pdfDoc = new System.IO.FileInfo(@'C:/SalesOrder.pdf');
//Initiallize the byte array by setting the length of the file
pdfDocBuffer= new System.Byte[int642int(fi_pdfDoc.get_Length())]();
// Stream the file
fs= new System.IO.FileStream(fi_pdfDoc.get_FullName(), System.IO.FileMode::Open, System.IO.FileAccess::Read);
fs.Read(pdfDocBuffer, 0, pdfDocBuffer.get_Length());
// Convert the file into a base64 string
Content = System.Convert::ToBase64String(pdfDocBuffer, 0, pdfDocBuffer.get_Length());
//Revert the access

Thats it done..................Now njoy converting any file into a base64 string from AX.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.