我正在尝试在.net core中生成带密码的zip(或其他压缩格式)文件,但是我找不到任何不带成本的工具。
我已经尝试了System.IO.Compression
,但它没有带密码的方法。
我正在尝试在.net core中生成带密码的zip(或其他压缩格式)文件,但是我找不到任何不带成本的工具。
我已经尝试了System.IO.Compression
,但它没有带密码的方法。
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
现在支持.net Core了。请查看Nuget获取更多详细信息。(同时,System.IO.Compression仍不支持密码保护)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;
dotnetzip
这样的东西适用于.net Core**。 - Johna