Wednesday, November 30, 2022

D365FO: Zip/Unzip memory stream to byte[] array X++

Sometimes we have to deal with big file streams, during that scenario there is an option to zip/unzip the file using gzip in X++.

for example: Pass files larger than 25MB to logic apps, logic app has a file size limit of 25 MB
using System.IO;
using System.IO.Compression;


class ZipUnzip
{
    public static System.Byte[] Compress(System.Byte[] data)
    {
        var compressedStream = new MemoryStream();
        var zipStream = new GZipStream(compressedStream, CompressionMode::Compress);
        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        return compressedStream.ToArray();
    }

    public static System.Byte[] Decompress(System.Byte[] data)
    {
        var compressedStream = new MemoryStream(data);
        var zipStream = new GZipStream(compressedStream, CompressionMode::Decompress);
        var resultStream = new MemoryStream();

        System.Byte[] buffer = new System.Byte[4096]();
        int read;

        do
        {
            read = zipStream.Read(buffer, 0, buffer.Length);
            resultStream.Write(buffer, 0, read);
        }
        while(read);

        return resultStream.ToArray();
    }

}

No comments:

Post a Comment

Table browser URL in D365FO

Critical Thinking icon icon by Icons8