Read Files from Zip Folder in D365 using System.IO.Compression Namespace

Hi All ,
In this blog post we will see how to use System.IO.Compression Namespace to read files from Zip folder.
The System.IO.Compression namespace contains classes that provide basic compression and decompression services for streams.
I came across requirement where I had to read files from zip folder containing data for payroll and import it in Journals. Following piece of code will give you idea about how to use compression namespace to get count of the files with in folder , how to  extract file from zip folder and copy to stream object which can be used further for reading content of the file.

void processZipFile()
    {
        #File

        FileUpload fileUploadControl = this.getFormControl(dialog, FileUploadName);
        
        FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();
        
        if (fileUploadResult != null && fileUploadResult.getUploadStatus())
        {
            zipFileName = fileUploadResult.getDownloadUrl();
        }

        //package of compressed files in the zip archive format
        System.IO.Compression.ZipArchive zipArchive =
            new System.IO.Compression.ZipArchive(File::UseFileFromURL(fileUploadResult.getDownloadUrl()), System.IO.Compression.ZipArchiveMode::Read);
        
        CLRObject archiveEntries =  zipArchive.get_Entries();
        //TO get coount of files with in Folder
        int length = archiveEntries.get_Count();

        List uploadUrlList = new List(types::Container);
        container consUnzippedFile;
        int i;

        for(i = 0; i < length; i++)
        {
            System.IO.Compression.ZipArchiveEntry item = archiveEntries.get_Item(i);
            List fileNameComponents = strSplit(item.Name, #FileExtensionDelimiter);
            ListIterator iterator = new ListIterator(fileNameComponents);
                                  
            using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                item.Open().CopyTo(stream);// copy File to stream, which can be used further to Read file line by line using ListEnumerator class
                info(strFmt("File Name : %1",item.Name));
            }
            
        }
        
    }

Comments

Popular posts from this blog

Running runnable class through URL in Dynamics 365 for Operations

D365FO Use of FileUpload control to Read CSV file

D365FO Send Report as email attachment