Search code examples
c#.neticsharpcode

icsharpcode SharpZipLib is not setting password correctly on zip file


The zip file appears to be created successfully on my drive, and contains the files I specified in filePaths[]

The issue is the that despite setting a password to 'hello' it will say the password is incorrect when I try and unzip the file.

/// <summary>
    /// Creates a zip file
    /// </summary>
    /// <param name="filePaths">An array of files to add to the zip file</param>
    /// <param name="password">Password of zip file. Set to null to ignore</param>
    /// <param name="outputName">The name of the outputted zip file (including full path) </param>
    /// <returns></returns>
    public string CreateZip(string[] filePaths, string password, string outputName)
    {
        outputName += ".zip";

        using (var file = ZipFile.Create(outputName))
        {
            file.BeginUpdate();

            filePaths.ToList().ForEach(x =>
            {
                if (Path.HasExtension(x))
                {
                    file.Add(x);
                }

                else if (!Path.HasExtension(x) && Directory.Exists(x))
                {
                    Directory.GetFiles(x, "*.*", SearchOption.AllDirectories).ToList().ForEach(file.Add);
                }
            });

            file.Password = password;

            file.CommitUpdate();
            file.Close();

        }

        return outputName;
    }

Interestingly, this problem only happens when the size of the file inside the zip is 0 bytes (it's an empty xml file).

If I add contents to the .xml file and try and zip it using my function, it doesn't ask for the password at all, despite specifying one in the code. (even more interesting is it asked me for the password after resetting my computer, and it worked correctly, but then have deleting all the files and trying again it doesn't ask for the password when unzipping)


Solution

  • I tested your code and reproduced the issue. Settings UseZip64 to On before commit did the trick for me:

    file.Password = password;
    
    file.UseZip64 = UseZip64.On;
    
    file.CommitUpdate();
    file.Close();
    

    When it is Dynamic or Off it gives the same error on empty files.