From 3e32e3d7b149a4e519e817ea578943d4096bb642 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 2 Sep 2021 13:54:32 +0200 Subject: [PATCH] Allowing to seek empty zip files --- .../Common/Zip/SeekableZipHeaderFactory.cs | 3 ++- .../SharpCompress.Test/Zip/ZipArchiveTests.cs | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs b/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs index 86eb7d081..b24f045ba 100644 --- a/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs +++ b/src/SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs @@ -117,7 +117,8 @@ private static void SeekBackToHeader(Stream stream, BinaryReader reader) // Search in reverse Array.Reverse(seek); - var max_search_area = len - MINIMUM_EOCD_LENGTH; + // don't exclude the minimum eocd region, otherwise you fail to locate the header in empty zip files + var max_search_area = len; // - MINIMUM_EOCD_LENGTH; for( int pos_from_end = 0; pos_from_end < max_search_area; ++pos_from_end) { diff --git a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs index ec710c761..6412ff750 100644 --- a/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs +++ b/tests/SharpCompress.Test/Zip/ZipArchiveTests.cs @@ -290,6 +290,28 @@ public void Zip_Create_New() Directory.Delete(SCRATCH_FILES_PATH, true); } + /// + /// Creates an empty zip file and attempts to read it right afterwards. + /// Ensures that parsing file headers works even in that case + /// + [Fact] + public void Zip_Create_Empty_And_Read() + { + var archive = ZipArchive.Create(); + + var archiveStream = new MemoryStream(); + + archive.SaveTo(archiveStream, CompressionType.LZMA); + + archiveStream.Position = 0; + + var readArchive = ArchiveFactory.Open(archiveStream); + + var count = readArchive.Entries.Count(); + + Assert.Equal(0, count); + } + [Fact] public void Zip_Create_New_Add_Remove() {