How to add a folder to a zip archive using ICSharpCode.SharpZipLib

I need to create two folders inside a zip file that I programmatically create 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 to create a directory using ZipEntry and how to add files to a directory located inside the Zip archive?

+6
source share
3 answers

I understood:

  • You can simply do new ZipEntry("Folder1/Archive.txt"); and new ZipEntry("Folder2/Archive2.txt");
+11
source

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

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

Here is 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 the folders as if they were files with ZipEntry, and put a slash in the end. It is working. I tested it.

+2
source

The best solution in our project was to switch to the best way.

https://dotnetzip.codeplex.com

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

methods are more straightforward to use

0
source

Source: https://habr.com/ru/post/952223/


All Articles