Create a zipped file using x++

 This article explains how we can create a zipped file in x++ and allow the file to be downloaded using the browser download.

For this example, I am adding a csv file to a zipped archive.

First we will need to create a stream with the contents for the csv file.

CommaStreamIo streamIO = CommaStreamIo::constructForWrite(); 

streamIO.writeExp('Id', 'Title'); // These will represent the header of the csv file 

streamIO.writeExp('001', 'Science'); // Row 1

streamIO.writeExp('002', 'Nature'); // Row 2

Next, we can generate the csv file contents and add it to a zip archive.
// Get the stream
System.IO.Stream        stream              = streamIO.getStream();
const str               extensionCsv        = '.csv';
const str               extensionZip        = '.zip';

System.IO.MemoryStream zipFileContents     = new System.IO.MemoryStream();
stream.Position     = 0;

// StreamReader to read as str
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
str csvFileContent = reader.ReadToEnd();

// zip the file
using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(zipFileContents, System.IO.Compression.ZipArchiveMode::Create, true))
{
    // Creates the file entry in the zip folder.
    System.IO.Compression.ZipArchiveEntry fileEntry = zipArchive.CreateEntry(csvFileName + extensionCsv);

    var entryStream =  fileEntry.Open();
    using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(entryStream))
    {
        streamWriter.Write(csvFileContent);
        streamWriter.Flush();
    }
}

zipFileContents.Position = 0;

// This line will allow the file to be auto downloaded via the browser on the client machine
File::SendFileToUser(zipFileContents, 'ZippedFile' + extensionZip);

Comments

Popular posts from this blog

D365FO - Create a multi-select lookup in batch jobs

Generate and download a csv file using X++

Creating a batch job with query based filter in D365 back-office