在.NET Core中使用密码压缩文件

12

我正在尝试在.net core中生成带密码的zip(或其他压缩格式)文件,但是我找不到任何不带成本的工具。

我已经尝试了System.IO.Compression,但它没有带密码的方法。


Zip是一种开放格式,对于.NET有几个免费的实现(尝试dotnetzip),支持加密。Rar和7z是专有的,我不知道有任何免费的库支持它们,因为必须获得许可证。 - Kevin
谢谢你,Kevin。我需要用在**.net Core**上,dotnetzip支持.net framework但不支持.net Core。 我将修改我的问题以使其更清晰。 - Johna
1
谢谢,但是那个适用于_.Net Framework_,我正在使用**.net Core,而且我找不到任何像dotnetzip这样的东西适用于.net Core**。 - Johna
@Johna,你最终做了什么? - R4nc1d
1
@Neel,请查看下面的答案。 - R4nc1d
显示剩余3条评论
2个回答

7
使用 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();
    }
}

好的,非常感谢。顺便问一下,如果文件很大,内存流会有问题吗? - Neel
@Neel,是的,我们有8MB的限制,MemoryStream会将整个文件加载到内存中。如果我必须下载更大的文件,我可能会使用Stream。但我想你已经知道了 :-) - R4nc1d
1
谢谢。8 MB 大小是可以的,没错。这会将整个文件加载到内存中。对于 .Net Core,这个解决方案适用于大文件:https://blog.stephencleary.com/2016/11/streaming-zip-on-aspnet-core.html - Neel
您需要添加命名空间 ICSharpCode.SharpZipLib.Zip 才能运行此代码。 - Fer R

3
好消息是,DotNetZip现在支持.net Core了。请查看Nuget获取更多详细信息。(同时,System.IO.Compression仍不支持密码保护)
我已经在.Net Core 3.1中使用了1.16.0版本,它可以很好地工作。
简要教程:
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);
                }

不要忘记在您的项目中添加DotNetZip Nuget包,并导入using Ionic.Zip;


2
哇,太棒了,感謝@亞鯉斯多德分享這個消息。 - Johna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接