使用密码在.net核心中压缩文件

Joh*_*hna 5 c# compression asp.net-core

我正在尝试使用密码在.net核心中生成zip(或其他压缩格式)文件,但我找不到任何费用.

我正在使用,System.IO.Compression但它没有密码方法.

我只找到了这个工具Chilkat,但它不是免费的.

谁能帮我?

谢谢!

R4n*_*c1d 6

使用SharpZipLib.NETStandard NuGet包。

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();
    }
}
Run Code Online (Sandbox Code Playgroud)