Telerik Forums
Telerik Document Processing Forum
0 answers
192 views
     public void UnzipTSWFiles(string sourceDirectory, string destinationDirectory, string password)
        {
            DefaultEncryptionSettings protectionSettings = new DefaultEncryptionSettings() { Password = password };

                 using (ZipArchive zipArchive = new ZipArchive(output, ZipArchiveMode.Read, true, null, null, protectionSettings))
                        {
                            foreach (ZipArchiveEntry entry in zipArchive.Entries)
                            {
                                using (Stream entryStream = entry.Open())
                                using (FileStream fileStream = File.OpenWrite(string.Format("{0}/{1}", targetDirectory, entry.FullName)))
                                {
                                    entryStream.CopyTo(fileStream);
                                }
                            }
                        }
                    
         

        }
purushotham
Top achievements
Rank 1
 asked on 09 Aug 2023
1 answer
511 views

Good morning,

I have a process which successfully generates a number of PDFs in a folder, and then compresses that folder into an unencrypted zip file.

I have used the code from a previous question:

https://www.telerik.com/forums/zip-content-of-a-folder-into-an-encrypted-zip-file

So my code is as follows:

public static void CreateZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName)

        {

            char[] directorySeparatorChar = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };

 

            ZipArchiveMode archiveMode = System.IO.File.Exists(destinationArchiveFileName) ? ZipArchiveMode.Update : ZipArchiveMode.Create;

 

            if (!string.IsNullOrEmpty(sourceDirectoryName))

            {

                using FileStream archiveStream = System.IO.File.Open(destinationArchiveFileName, FileMode.OpenOrCreate);

                using ZipArchive archive = new ZipArchive(archiveStream, archiveMode, leaveOpen: false, entryNameEncoding: null);

                foreach (string fileName in Directory.GetFiles(sourceDirectoryName))

                {

                    using FileStream file = System.IO.File.OpenRead(fileName);

                    int length = fileName.Length - sourceDirectoryName.Length;

                    string entryName = fileName.Substring(sourceDirectoryName.Length, length);

                    entryName = entryName.TrimStart(directorySeparatorChar);

 

                    using ZipArchiveEntry entry = archive.CreateEntry(entryName);

                    using Stream entryStream = entry.Open();

                    file.CopyTo(entryStream);

                }

            }

        }

This creates the zip file and adds the first PDF successfully, but gives an error when trying to add the second PDF

"The process cannot access the file 'filename.zip' because it is being used by another process."

I have tried setting the leaveOpen parameter for the ZipArchive to true and to false but that gives me the same error.

Any ideas what I've missed?

Richard

 

Dimitar
Telerik team
 answered on 01 Dec 2021
1 answer
699 views

Hi,

 

Is there a way to overwrite existing files when unpacking from a zip with ZipFile.ExtractToDirectory()?

 

Thanks,

Marc

Tanya
Telerik team
 answered on 07 May 2021
7 answers
1.0K+ views
Hi Telerik Team,

I was able to use ZipPackage to zip all the files that I have in a folder into a new zip file.
Note: The folder contains different file types .zip, .pdf, .xlsx .docx and .txt
However a new requirement is to encrypt the main zip file so no one can access the content of the file without having the password.
I have seen the sample below but I don't know how to get it to work with different existing binary files like PDF.

using (Stream stream = File.Open("test.zip", FileMode.Create))
{
    using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, false, null))
    {
        using (ZipArchiveEntry entry = archive.CreateEntry("text.txt"))
       {
            StreamWriter writer = new StreamWriter(entry.Open());
            writer.WriteLine("Hello world!");
            writer.Flush();
        }
    }
}

Can you help?
Peshito
Telerik team
 answered on 04 Mar 2021
7 answers
158 views

Hi,

I would like to export some excel files in a zip without writing on disk.

I have seen ZipLibrary example and I would like to adapt it with excel (if possible).

The idea is to do something like this in "OnClick" event for exemple (see code bellow)

Thanks in advance for your help

using (MemoryStream stream = new MemoryStream())
{
    using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null))
    {
        //I don't need TXT but just for testing ...
        using (ZipArchiveEntry entry = archive.CreateEntry("text1.txt"))
        {
            StreamWriter writer = new StreamWriter(entry.Open());
            writer.WriteLine("Hello world!");
            writer.Flush();
        }
 
        //Adding excel file
        using (ZipArchiveEntry entry = archive.CreateEntry("testxlsx.xlsx"))
        {
            //How to handle / edit XLSX file here ?
        }
    }
 
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=zipfile.zip");
    Response.ContentType = "application/zip";
    Response.BinaryWrite(stream.ToArray());
    Response.End();
}
Julien
Top achievements
Rank 1
 answered on 13 Jan 2021
6 answers
88 views

When creating a password-protected ZIP archive, if I create a new entry and write to it, and during this process create, write and close a second entry, then the first entry appears to be corrupt when you try to read the file.

For example, the following see the following program:

static void Main(string[] args)
{
    // Create the main ZIP file
    using (var zipStream = File.Create(@"c:\temp\test.zip"))
    {
        var encrypt = new DefaultEncryptionSettings { Password = "nick" };
        using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create,true,null,null,encrypt))
        {
            // Create the 1st entry.
            using (var entry1 = zipArchive.CreateEntry("text1.txt"))
            {
                using (var stream1 = entry1.Open())
                {
                    using (var writer1 = new StreamWriter(stream1))
                    {
                        writer1.WriteLine("Writer 1 line 1");
                        // While writing the 1st entry, create a second entry
                        using (var entry2 = zipArchive.CreateEntry("text2.txt"))
                        {
                            using (var stream2 = entry2.Open())
                            {
                                using (var writer2 = new StreamWriter(stream2))
                                {
                                    writer2.WriteLine("Writer 2 line 1");
                                }
                            }
                        }
                        // Continue writing the 1st entry.
                        writer1.WriteLine("Writer 1 line 2");
                    }
                }
            }
 
        }
    }
}

 

This runs without error. Opening the file using 7-zip, I can read the "text2.txt" entry with no problem with the correct password. However, opening the "text1.txt" file gives an error suggesting the password is wrong.

Program in .NET 4.6, using Telerik.Windows.Zip 2018.3.1010.40.

Martin
Telerik team
 answered on 29 Sep 2020
2 answers
371 views

I'm using Telerik in an interop environment with C++ and trying to replace our old ZIP library.  With the code below it appears to ZIP all files correctly except the last file always has some error with it like it isn't being written out properly.  I've changed the number and type of files and the specific file type doesn't matter, the last one in the archive is always corrupted when i test the archive.

 

    System::String^ sSource = gcnew System::String(m_sPath1);
        System::String^ sDest = gcnew System::String(sZipDest);
        
        System::IO::File^ file = nullptr;
        System::IO::Stream^ stream = file->Open(sDest, System::IO::FileMode::Create);
        Telerik::Windows::Zip::ZipArchive^ zarchive = gcnew Telerik::Windows::Zip::ZipArchive(stream, Telerik::Windows::Zip::ZipArchiveMode::Create,false,System::Text::Encoding::UTF8);
         
        Telerik::Windows::Zip::DeflateSettings^ compressionSettings = gcnew Telerik::Windows::Zip::DeflateSettings();
        compressionSettings->CompressionLevel = Telerik::Windows::Zip::CompressionLevel::Best;
        compressionSettings->HeaderType = Telerik::Windows::Zip::CompressedStreamHeader::ZLib;
 
        pList3->ResetContent();
        rc = 0;
        nCount = pList1->GetCount();
        for (n = 0; n<nCount; n++) {
            pList1->GetText(n, sFileName);
            sFullyQualifiedFileNameFrom = fs.AppendWildcard(m_sPath1, sFileName);
            int nSel = pList3->AddString(sFileName);
            pList3->SetCurSel(nSel);
            pList3->UpdateWindow();
            System::String^ sFull = gcnew System::String(sFullyQualifiedFileNameFrom.GetBuffer());
            System::String^ sName = gcnew System::String(sFileName.GetBuffer());
            Telerik::Windows::Zip::Extensions::ZipFile::CreateEntryFromFile(zarchive, sFull, sName, compressionSettings);
            int nFilesPercent = 100 * (n + 1) / nCount;
            m_prStatus.SetPos(nFilesPercent);
        }
        Sleep(5000);
        stream->Flush();
        stream->Close();

 

Is there something else that should be done to finish the compression/writing of the last file when in the loop using CreateEntryFromFile?  

Martin
Telerik team
 answered on 13 May 2020
1 answer
80 views

hi sir,

 

              I compress the main level with five level of sub folder using telerik it compress in to one single folder.But i want same like as before compress(i want to follow same folder structure while extract).

the below image show as original

http://prntscr.com/o7djqa

this one i need

http://prntscr.com/o7dkmt

but it show 

http://prntscr.com/o7dkmt

i send the project it has two button button one work i use oridanry zip format but button2 not work properly i use telerik

https://www.dropbox.com/s/i5pwsbbthkab5jy/WebSitesss.rar?dl=0

 

Tanya
Telerik team
 answered on 02 Jul 2019
5 answers
114 views
Hi.

I have recently started using the ZipLibrary and I am facing an issue when adding streams to a ZipPackage.  I am trying to add two streams to the ZipPackage, one for a PowerPoint file and the other for a Excel file.  Once it is packaged, I want to write it to the OutputStream.  Before I add the streams to the package, their size is significantly larger and have data because when I export them as individual streams (outside of a zip) it works just fine.  Once added it looks like they lose all of their data and when it outputs, the PPTX and XLSX files are empty and corrupt respectively.

Here is my code below as well as the SendZipToClient snippet from another forum post, is there anything wrong with it or is it an issue from the ZipLibrary?

Additional Info:
.NET version: 4.5
Current Browser: FireFox 21.0
Telerik version for ASP.NET AJAX: 2013.1.417.45
Language: C#


private void StreamReports(Dictionary<int, MemoryStream> ReportStreams)
{
      string destPPTXFile = string.Format("{0}.pptx", txtPresentationName.Text);
      string destXLSXFile = string.Format("{0}.xlsx", txtPresentationName.Text);
 
      MemoryStream outputStream = new MemoryStream();
      ZipPackage zipPackage = ZipPackage.Create(outputStream);
 
      MemoryStream powerpointStream = ReportStreams[0];
      MemoryStream excelStream = ReportStreams[1];
 
      zipPackage.AddStream(powerpointStream, destPPTXFile);
      zipPackage.AddStream(excelStream, destXLSXFile);
 
      SendZipToClient(outputStream, zipPackage);
 
 }

private void SendZipToClient(MemoryStream memStream, ZipPackage Package)
        {
            string destFile = string.Format("{0}.zip", txtPresentationName.Text);
            Package.Close(false);
            memStream.Position = 0;
            if (memStream != null && memStream.Length > 0)
            {
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=\"" + destFile);
                Response.ContentType = "application/zip";
                Response.BufferOutput = false;   // to prevent buffering
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = memStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Response.OutputStream.Write(buffer, 0, bytesRead);
                }
 
                Response.End();
            }
        }
Tom
Top achievements
Rank 1
 answered on 18 Sep 2018
3 answers
126 views
Language: VB.NET

Hello,

I'm looking to use CompressedStream solution without really understanding its use.

What I am trying to do:
1. compress file.
2. Insert the compressed file into my Database.
3. Retrieve compressed file to unzip it.
4. Read file.

How can I efficiently compress the file ?
Which method should I use ?
What type of variable should I deal with ? (String, Byte ()?)

Would you have a functional example in .net to help me ?

Thanks for your help
Tanya
Telerik team
 answered on 07 Sep 2018
Narrow your results
Selected tags
Tags
+? more
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?