使用SharpZipLib插件 插件地址:http://icsharpcode.github.io/SharpZipLib/
using ICSharpCode.SharpZipLib.Zip; public static void BatchDownFile(List<string> urlList) { /*删除之前的临时文件*/ string path = Path.Combine(privateDiskBasePath,"tempZip"); DirectoryInfo dirInfo = new DirectoryInfo(path); if (dirInfo.Exists) { dirInfo.Delete(true); } dirInfo.Create(); string fileName = Path.Combine(path, "打包文件.zip"); using (ZipFile zip = ZipFile.Create(fileName)) { zip.BeginUpdate(); zip.SetComment("压缩包"); foreach (var item in urlList) { if (File.Exists(item))//判断是文件还是文件夹 { byte[] buffer = null; try { buffer = File.ReadAllBytes(item); } catch { } if (buffer != null && buffer.Length > 0) { StreamDataSource dataSource = new StreamDataSource(buffer); string[] fileNameSplit = item.Split('\'); zip.Add(dataSource, fileNameSplit[fileNameSplit.Length - 1]); } } } zip.CommitUpdate(); } DownFile("打包文件.zip", fileName); }
public class StreamDataSource : IStaticDataSource { public byte[] Buffer { get; private set; } public StreamDataSource(byte[] buffer) { Buffer = buffer; } public Stream GetSource() { return new MemoryStream(Buffer); } }
public static void BatchDownFile(List<string> urlList, int userId) { string privateDiskBasePath = string.Empty; /*删除之前的临时文件*/ string path = Path.Combine(privateDiskBasePath, userId.ToString(), "tempZip"); DirectoryInfo dirInfo = new DirectoryInfo(path); if (dirInfo.Exists) { dirInfo.Delete(true); } dirInfo.Create(); string zipFileName = Path.Combine(path, "打包文件.zip"); using (FileStream fs = File.Create(zipFileName)) { using (ZipOutputStream zipStream = new ZipOutputStream(fs)) { foreach (var item in urlList) { using (FileStream toZipFs = new FileStream(item, FileMode.Open, FileAccess.Read)) { string fileName = item.Substring(item.LastIndexOf("\") + 1); ZipEntry zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(5);//设置压缩等级 byte[] buffer = new byte[2048]; int sizeRead = 0; try { do { sizeRead = toZipFs.Read(buffer, 0, buffer.Length); zipStream.Write(buffer,0, sizeRead); } while (sizeRead > 0); } catch (Exception) { throw; } toZipFs.Close(); } } zipStream.Finish(); zipStream.Close(); } fs.Close(); } }