多文件打压成一个ZIP包
调用方法:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace ZipRar{ static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { //打包 List<string> listFile = new List<string>(); listFile.Add(System.Environment.CurrentDirectory @"\Data\EquimentInfo.ini"); listFile.Add(System.Environment.CurrentDirectory @"\Data\BuildingEnergy.ini"); listFile.Add(System.Environment.CurrentDirectory @"\Data\parse.ini"); listFile.Add(System.Environment.CurrentDirectory @"\Data\terminalinfo.ini"); listFile.Add(System.Environment.CurrentDirectory @"\Data\publicdatapara.db"); listFile.Add(System.Environment.CurrentDirectory @"\Data\VarInfo.db"); commonUtil.ZipFile(listFile, System.Environment.CurrentDirectory @"\Data\Config.zip", 2); } }}
下为核心代码:
/// <summary> /// 压缩duo个文件 /// </summary> /// <param name="fileToZip">要进行压缩的文件名</param> /// <param name="zipedFile">压缩后生成的压缩文件名</param> public static void ZipFile(List<string> fileToZipS, string zipedFile, int Level) { foreach (string fileToZip in fileToZipS) { //如果文件没有找到,则报错 if (!File.Exists(fileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " fileToZip " 不存在!"); break; } } using (FileStream ZipFile = File.Create(zipedFile)) { using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile)) { foreach (string fileToZip in fileToZipS) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") 1); using (FileStream fs = File.OpenRead(fileToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); ZipEntry ZipEntry = new ZipEntry(fileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(Level); ZipStream.Write(buffer, 0, buffer.Length); } } ZipStream.Finish(); ZipStream.Close(); } } }
评论