Requirement : The requirement is to create a zip file from a set of document entries available in document handling, creating a download link and sends the link to user browser.
In this requirement we are using Microsoft Dynamics 365 for finance and operations classes – documentmanagement, ziparchive & ziparchiveentry.
Sample Code :
class RunnableClassZIP
{
/// <summary>
/// Runs the class with the specified arguments.
/// </summary>
/// <param name = "_args">The specified arguments.</param>
public static void main(Args _args)
{
System.IO.Stream fileStream;
System.IO.MemoryStream zipArchiveStream = new System.IO.MemoryStream();
DocuRef docuRef;
DocuValue docuValue;
const str extensionZip = '.zip';
const str zipFileName = 'myZipfile';
using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(
zipArchiveStream,
System.IO.Compression.ZipArchiveMode::Create,
true))
{
while select docuRef
join docuValue
where docuValue.RecId == docuRef.ValueRecId
&& docuRef.RefTableId == 'your table id'
&& docuRef.RefRecId == 'your rec id'
{
// Creates the file entry in the zip folder.
System.IO.Compression.ZipArchiveEntry fileEntry = zipArchive.CreateEntry(docuValue.filename());
// Opens the created file entry and copies the binary file information of the original file to the file entry in the zip folder.
using (System.IO.Stream fileEntryStream = fileEntry.Open())
{
// Gets the file stream of the document attachment.
fileStream = DocumentManagement::getAttachmentStream(docuRef);
fileStream.CopyTo(fileEntryStream);
}
}
// Send a download link of the created zip folder to the user.
File::SendFileToUser(zipArchiveStream, zipFileName + extensionZip);
}
}
}
2 thoughts on “D365 Fin & Ops : ZIP, Compress & Archive multiple files using X++ & class ZipArchiveEntry”