C#将文件流打成zip包

1.在 .NET Core 中,结合 System.IO.Compression 命名空间和 System.IO 命名空间中的 FileStream 类、ZipFile 类可以实现将多个文件流压缩成一个 zip 文件流的功能。具体实现如下:
        public async Task<FileViewDto> ExportUploadFileZipAsync(List<long> ids)
        {
            var streams = new Dictionary<string, Stream>();

            foreach (var id in ids) 
            {
                var data = await ExportUploadFileAsync(id);

                string fileName = System.IO.Path.GetFileNameWithoutExtension(data.Name); // 文件名
                string extension = System.IO.Path.GetExtension(data.Name); // 扩展名(包括点)

                Stream stream = new MemoryStream(data.Content);
                streams.Add($"{fileName}_{DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmssfff")}{extension}", stream);
            }

            byte[] fileBytes = CompressStreamsToZip(streams); // 调用压缩方法

            return new FileViewDto
            {
                Name = $"{DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss")}.zip",
                Content = fileBytes,
                ContentType = "application/zip"
            };
        }

        private byte[] CompressStreamsToZip(IDictionary<string, Stream> streams)
        {
            // 创建一个新的 zip 文件流
            var zipStream = new MemoryStream();

            try
            {
                // 创建一个新的 zip 文件
                using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
                {
                    foreach (var kvp in streams)
                    {
                        // 添加一个新的 zip 文件条目
                        var entry = zipArchive.CreateEntry(kvp.Key);

                        // 将文件流写入 zip 文件条目中
                        using (var entryStream = entry.Open())
                        {
                            kvp.Value.CopyTo(entryStream);
                        }
                    }
                }

                // 将 zip 文件流返回
                zipStream.Seek(0, SeekOrigin.Begin);
            }
            catch (Exception ex)
            {
                _logger.LogError($"压缩文件出错,错误信息:{ex.Message}");
            }

            return zipStream.ToArray();
        }
2.第二种方法
        /// 
        /// ZipStream 压缩
        /// 
        /// Dictionary(string, Stream) 文件名和Stream
        /// 
        public byte[] ConvertZipStream(Dictionary<string, Stream> streams)
        {
            byte[] buffer = new byte[6500];
            MemoryStream returnStream = new MemoryStream();
            var zipMs = new MemoryStream();
            using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMs))
            {
                zipStream.SetLevel(9);//设置 压缩等级 (9级 500KB 压缩成了96KB)
                foreach (var kv in streams)
                {
                    string fileName = kv.Key;
                    using (var streamInput = kv.Value)
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                        zipEntry.IsUnicodeText = true;
                        zipStream.PutNextEntry(zipEntry);

                        while (true)
                        {
                            var readCount = streamInput.Read(buffer, 0, buffer.Length);
                            if (readCount > 0)
                            {
                                zipStream.Write(buffer, 0, readCount);
                            }
                            else
                            {
                                break;
                            }
                        }
                        zipStream.Flush();
                    }
                }
                zipStream.Finish();
                zipMs.Position = 0;
                zipMs.CopyTo(returnStream, 5600);
            }
            returnStream.Position = 0;

            //Stream转Byte[]
            byte[] returnBytes = new byte[returnStream.Length];
            returnStream.Read(returnBytes, 0, returnBytes.Length);
            returnStream.Seek(0, SeekOrigin.Begin);

            return returnBytes;
        }
var streams = new Dictionary<string, Stream>();

//调用压缩方法 进行压缩 (接收byte[] 数据)
 byte[] fileBytes = ConvertZipStream(streams);

你可能感兴趣的:(C#,c#,开发语言)