SharpZipLib icon indicating copy to clipboard operation
SharpZipLib copied to clipboard

Can't open empty file

Open MagnusBeijer opened this issue 1 year ago • 2 comments

Describe the bug

If a zip file is created without adding any files to it, it can not be opened and throws: ICSharpCode.SharpZipLib.Zip.ZipException: Cannot find central directory

Steps to reproduce

    using (var b = ZipFile.Create("c:\\temp\\sharpzip.zip")) { }
    using (var b = new ZipFile("c:\\temp\\sharpzip.zip")) { } // Throws exception

Expected behaviour

The file should be opened and contain no files.

Operating System

Windows

Framework Version

.NET 7

Tags

ZIP

Additional context

No response

MagnusBeijer avatar Sep 19 '24 06:09 MagnusBeijer

	public ZipFile(string name, StringCodec stringCodec)
	{
		name_ = name ?? throw new ArgumentNullException(nameof(name));

		baseStream_ = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read);
		isStreamOwner = true;

		if (stringCodec != null)
		{
			_stringCodec = stringCodec;
		}

		if (baseStream_.Length > 0)
		{
			try
			{
				ReadEntries();
			}
			catch
			{
				DisposeInternal(true);
				throw;
			}
		}
		else
		{
			entries_ = Empty.Array<ZipEntry>();
			isNewArchive_ = true;
		}
	}


	public ZipFile(FileStream file, bool leaveOpen)
	{
		if (file == null)
		{
			throw new ArgumentNullException(nameof(file));
		}

		if (!file.CanSeek)
		{
			throw new ArgumentException("Stream is not seekable", nameof(file));
		}

		baseStream_ = file;
		name_ = file.Name;
		isStreamOwner = !leaveOpen;

		if (baseStream_.Length > 0)
		{
			try
			{
				ReadEntries();
			}
			catch
			{
				DisposeInternal(true);
				throw;
			}
		}
		else
		{
			entries_ = Empty.Array<ZipEntry>();
			isNewArchive_ = true;
		}
	}

This is the fix.

jagmehta avatar Sep 29 '24 16:09 jagmehta

Doing this ensures that the central directory gets created:

using (var zipFile = ZipFile.Create("c:\\temp\\sharpzip.zip"))
{
    zipFile.BeginUpdate();
    zipFile.CommitUpdate();
 }

MagnusBeijer avatar Sep 30 '24 06:09 MagnusBeijer