[英]Zip files in .net core with password
I'm trying to generate zip (or other compression formats) files in .net core with password, but I can't find any tool that does not come without a cost.我正在尝试使用密码在.net 核心中生成 zip(或其他压缩格式)文件,但我找不到任何不收费的工具。
I've tried System.IO.Compression
but it doesn't have a method with password.我试过System.IO.Compression
但它没有密码方法。
Using the SharpZipLib.NETStandard
NuGet package.使用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();
}
}
好消息是DotNetZip<\/code>现在支持 .net Core。检查Nuget<\/a>以获取更多详细信息。 (同时 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.