Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 313
Saturn K Avatar asked Aug 21 '13 16:08

Saturn K


2 Answers

I figured it out:

  • You can simply do new ZipEntry("Folder1/Archive.txt"); and new ZipEntry("Folder2/Archive2.txt");
like image 161
Saturn K Avatar answered Oct 31 '22 08:10

Saturn K


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.

like image 4
Christian Findlay Avatar answered Oct 31 '22 10:10

Christian Findlay