Zip files in .net core with password

Solution 1:

Using the SharpZipLib.NETStandard NuGet package.

public async Task<byte[]> ZipAsync(IEnumerable<KeyValuePair<string, Stream>> files, string mime, string password)
{
    ExceptionHelper.ThrowIfNull(nameof(files), files);
    ExceptionHelper.ThrowIfNull(nameof(mime), mime);

    using (var output = new MemoryStream())
    {
        using (var zipStream = new ZipOutputStream(output))
        {
            zipStream.SetLevel(9);

            if (!string.IsNullOrEmpty(password))
            {
                zipStream.Password = password;
            }

            foreach (var file in files)
            {
                var newEntry = new ZipEntry($"{file.Key}.{mime}") { DateTime = DateTime.Now };
                zipStream.PutNextEntry(newEntry);

                await file.Value.CopyToAsync(zipStream);
                zipStream.CloseEntry();
            }
        }

        return output.ToArray();
    }
}

Solution 2:

Good news is that DotNetZip supports .net Core now. Check Nuget for more details. (Meanwhile System.IO.Compression still doesn't support password protection)

I've used 1.16.0 version in .Net Core 3.1 and it works well.

Brief tutorial:

using (var zip = new ZipFile())
                {
                    zip.Password = pwd;
                    zip.AddEntry(FileA_Name, FileA_Content);
                    zip.AddEntry(FileB_Name, FileB_Content);
                    MemoryStream output = new MemoryStream();
                    zip.Save(output);
                    return File(output.ToArray(), "application/zip", Zip_Name);
                }

Don't forget to add DotNetZip Nuget package in your project, and import using Ionic.Zip;