Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't open empty file #879

Open
MagnusBeijer opened this issue Sep 19, 2024 · 2 comments
Open

Can't open empty file #879

MagnusBeijer opened this issue Sep 19, 2024 · 2 comments
Labels
bug zip Related to ZIP file format

Comments

@MagnusBeijer
Copy link

MagnusBeijer commented Sep 19, 2024

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

@github-actions github-actions bot added the zip Related to ZIP file format label Sep 19, 2024
@jagmehta
Copy link

	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.

@MagnusBeijer
Copy link
Author

Doing this ensures that the central directory gets created:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug zip Related to ZIP file format
Projects
None yet
Development

No branches or pull requests

2 participants