如何使用ICSharpCode.SharpZipLib将文件夹添加到zip存档

我必须在zip文件中创建两个文件夹,我使用ICSharpCode.SharZipLib.Zip编程方式创建。 我想要:

  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; } } 

如何使用ZipEntry创建目录,然后如何将文件添加到Zip存档内的目录?

我想到了:

  • 你可以简单地做一个new ZipEntry("Folder1/Archive.txt");new ZipEntry("Folder2/Archive2.txt");

上面的答案适用于多种情况,但是当您想要将空文件夹添加到zip文件时,它将无法工作。

我筛选了SharpZipLib代码,发现创建文件夹唯一需要做的就是ZipEntry名称上的尾随“/”正斜杠。

这是图书馆的代码:

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

因此,只需创建文件夹,就好像它们是ZipEntry文件一样,并在最后添加正斜杠。 有用。 我测试过了。

我们项目的最佳解决方案是切换到更好的方式

https://dotnetzip.codeplex.com

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

这些方法更直接使用