How do you add a folder to a zip archive with ICSharpCode.SharpZipLib
Asked Answered
N

3

8

I have to create two folders inside of a zip file that I create programmatically using ICSharpCode.SharZipLib.Zip. I want to:

    private void AddToZipStream(byte[] inputStream, ZipOutputStream zipStream, string fileName, string fileExtension)
    {
        var courseName = RemoveSpecialCharacters(fileName);

        var m_Bytes = inputStream;
        if ((m_Bytes != null) && (zipStream != null))
        {
            var newEntry = new ZipEntry(ZipEntry.CleanName(string.Concat(courseName, fileExtension)));
            newEntry.DateTime = DateTime.Now;
            newEntry.Size = m_Bytes.Length;

            zipStream.PutNextEntry(newEntry);
            zipStream.Write(m_Bytes, 0, m_Bytes.Length);
            zipStream.CloseEntry();
            zipStream.UseZip64 = UseZip64.Off;
        }
    }

How do I create a directory using ZipEntry and how do then add files to the directory located inside of the Zip archive?

Niobous answered 21/8, 2013 at 16:42 Comment(0)
N
18

I figured it out:

  • You can simply do new ZipEntry("Folder1/Archive.txt"); and new ZipEntry("Folder2/Archive2.txt");
Niobous answered 21/8, 2013 at 18:2 Comment(0)
H
4

The answer above will work for several scenarios, but it will not work when you want to add an empty folder to a zip file.

I sifted through the SharpZipLib code and found that the only thing you need to do to create a folder is a trailing "/" forward slash on the ZipEntry name.

Here's the code from the library:

public bool IsDirectory {
    get {
        int nameLength = name.Length;
        bool result =
            ((nameLength > 0) &&
            ((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) ||
            HasDosAttributes(16)
            ;
        return result;
    }
}

So, just create folders as though they are files with ZipEntry, and put a forward slash on the end. It works. I've tested it.

Henshaw answered 30/7, 2016 at 8:9 Comment(2)
Thank you for your comment. I didn't ask the question properly. What I really wanted to do is create a folder+file combination, which the answer that I gave works for.Niobous
Yes. I just added my comment because I was googling for an answer to adding an empty folder. Now people will find both answers.Henshaw
H
-2

The best solution at our project was to switch to the way better

https://dotnetzip.codeplex.com

https://github.com/haf/DotNetZip.Semverd

the methods are more straight forward to use

Heed answered 28/9, 2017 at 14:52 Comment(1)
As is the case with many companies, I didn't have a choice on the library to use. This lib was used for years. I'm not with the company any longer though :) so you bet I will use dotnetzip, specially semverd.Niobous

© 2022 - 2024 — McMap. All rights reserved.