前端页面代码:
<div> <asp:Button ID="sBtn6" runat="server" OnClick="sBtn6_Click" Text="ZIP压缩" /> <asp:Button ID="sBtn7" runat="server" OnClick="sBtn7_Click" Text="ZIP解压缩" /></div>
使用C#实例:
/// <summary> /// ZIP压缩 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void sBtn6_Click(object sender, EventArgs e) { urlPath = Server.MapPath("~/file/"); string zStr = GZipHelper.Compress("zhengdecai.com"); byte[] deskey = { 198, 125, 20, 111, 77, 71, 228, 9 }; //GZipHelper.Compress(deskey); GZipHelper.CompressFile(urlPath + "zhengdecai_bar.jpg", urlPath + "zhengdecai.zip"); GZipHelper.PackFiles(urlPath + "zhengdecai_bar.zip", urlPath + "zip/"); //GZipHelper.ZipFileDictory(urlPath + "zip/", urlPath, 5); GZipHelper.ZipFile(urlPath + "zhengdecai_bar.jpg", urlPath + "zheng_b.zip", 5); GZipHelper.Zip(urlPath + "zhengdecai_bar.jpg", urlPath + "zheng_c.zip", 5); GZipHelper gZipHelper = new GZipHelper(); //gZipHelper.EnZip("zhengdecai_bar.jpg", urlPath, urlPath); } /// <summary> /// ZIP解压缩 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void sBtn7_Click(object sender, EventArgs e) { urlPath = Server.MapPath("~/file/"); string zStr = GZipHelper.Compress("zhengdecai.com"); string cStr = GZipHelper.Uncompress(zStr); GZipHelper.DecompressFile(urlPath + "zhengdecai.zip", urlPath + "zhengdecai_bar.jpg"); GZipHelper.UnpackFiles(urlPath + "zhengdecai_bar.zip", urlPath + "zip/"); GZipHelper.UnZip(urlPath + "zheng_c.zip", urlPath); }
类库信息:
/// <summary> /// 压缩文本、字节或者文件的压缩辅助类 /// </summary> public class GZipHelper { #region 文本字符串、文件压缩操作 /// <summary> /// 压缩字符串 /// </summary> /// <param name="text">需要压缩文本内容</param> /// <returns></returns> public static string Compress(string text) { // convert text to bytes byte[] buffer = Encoding.UTF8.GetBytes(text); // get a stream MemoryStream ms = new MemoryStream(); // get ready to zip up our stream using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { // compress the data into our buffer zip.Write(buffer, 0, buffer.Length); } // reset our position in compressed stream to the start ms.Position = 0; // get the compressed data byte[] compressed = ms.ToArray(); ms.Read(compressed, 0, compressed.Length); // prepare final data with header that indicates length byte[] gzBuffer = new byte[compressed.Length + 4]; //copy compressed data 4 bytes from start of final header System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); // copy header to first 4 bytes System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); // convert back to string and return return Convert.ToBase64String(gzBuffer); } /// <summary> /// 解压字符串 /// </summary> /// <param name="compressedText">需解压的文本字符串</param> /// <returns></returns> public static string Uncompress(string compressedText) { // get string as bytes byte[] gzBuffer = Convert.FromBase64String(compressedText); // prepare stream to do uncompression MemoryStream ms = new MemoryStream(); // get the length of compressed data int msgLength = BitConverter.ToInt32(gzBuffer, 0); // uncompress everything besides the header ms.Write(gzBuffer, 4, gzBuffer.Length - 4); // prepare final buffer for just uncompressed data byte[] buffer = new byte[msgLength]; // reset our position in stream since we're starting over ms.Position = 0; // unzip the data through stream GZipStream zip = new GZipStream(ms, CompressionMode.Decompress); // do the unzip zip.Read(buffer, 0, buffer.Length); // convert back to string and return return Encoding.UTF8.GetString(buffer); } /// <summary> /// 将字符流进行压缩 /// </summary> /// <typeparam name="T">压缩实体格式</typeparam> /// <param name="stream">字符流</param> /// <param name="mode">压缩类型</param> /// <returns></returns> public static T GZip<T>(Stream stream, CompressionMode mode) where T : Stream { byte[] writeData = new byte[4096]; T ms = default(T); using (Stream sg = new GZipStream(stream, mode)) { while (true) { Array.Clear(writeData, 0, writeData.Length); int size = sg.Read(writeData, 0, writeData.Length); if (size > 0) { ms.Write(writeData, 0, size); } else { break; } } return ms; } } /// <summary> /// 压缩字节 /// </summary> /// <param name="bytData">字符串数组</param> /// <returns></returns> public static byte[] Compress(byte[] bytData) { using (MemoryStream stream = GZip<MemoryStream>(new MemoryStream(bytData), CompressionMode.Compress)) { return stream.ToArray(); } } /// <summary> /// 解压字节 /// </summary> /// <param name="bytData">字符串数组</param> /// <returns></returns> public static byte[] Decompress(byte[] bytData) { using (MemoryStream stream = GZip<MemoryStream>(new MemoryStream(bytData), CompressionMode.Decompress)) { return stream.ToArray(); } } /// <summary> /// 压缩文件 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="destinationFile">目标文件</param> public static void CompressFile(string sourceFile, string destinationFile) { if (File.Exists(sourceFile) == false) //判断文件是否存在 throw new FileNotFoundException(); if (File.Exists(destinationFile) == false) //判断目标文件文件是否存在 FileHelper.DeleteFile(destinationFile); //创建文件流和字节数组 byte[] buffer = null; FileStream sourceStream = null; FileStream destinationStream = null; GZipStream compressedStream = null; try { sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read); buffer = new byte[sourceStream.Length]; //把文件流存放到字节数组中 int checkCounter = sourceStream.Read(buffer, 0, buffer.Length); if (checkCounter != buffer.Length) { throw new ApplicationException(); } destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write); //创建GzipStream实例,写入压缩的文件流 compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true); compressedStream.Write(buffer, 0, buffer.Length); } finally { // Make sure we allways close all streams if (sourceStream != null) { sourceStream.Close(); } if (compressedStream != null) { compressedStream.Close(); } if (destinationStream != null) { destinationStream.Close(); } } } /// <summary> /// 解压文件 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="destinationFile">目标文件</param> public static void DecompressFile(string sourceFile, string destinationFile) { if (!File.Exists(sourceFile)) { throw new FileNotFoundException(); } FileStream stream = null; FileStream stream2 = null; GZipStream stream3 = null; byte[] buffer = null; try { stream = new FileStream(sourceFile, FileMode.Open); stream3 = new GZipStream(stream, CompressionMode.Decompress, true); buffer = new byte[4]; int num = ((int)stream.Length) - 4; stream.Position = num; stream.Read(buffer, 0, 4); stream.Position = 0L; byte[] buffer2 = new byte[BitConverter.ToInt32(buffer, 0) + 100]; int offset = 0; int count = 0; while (true) { int num5 = stream3.Read(buffer2, offset, 100); if (num5 == 0) { break; } offset += num5; count += num5; } stream2 = new FileStream(destinationFile, FileMode.Create); stream2.Write(buffer2, 0, count); stream2.Flush(); } finally { if (stream != null) { stream.Close(); } if (stream3 != null) { stream3.Close(); } if (stream2 != null) { stream2.Close(); } } } #endregion #region ICSharpCode.SharpZipLib、RAR压缩、解压文件 #region ICSharpCode.SharpZipLib普通解压缩 /// <summary> /// 压缩 /// </summary> /// <param name="filename"> 压缩后的文件名(包含物理路径)</param> /// <param name="directory">待压缩的文件夹(包含物理路径)</param> public static void PackFiles(string filename, string directory) { try { FastZip fz = new FastZip(); fz.CreateEmptyDirectories = true; fz.CreateZip(filename, directory, true, ""); fz = null; } catch (Exception) { throw; } } /// <summary> /// 解压缩 /// </summary> /// <param name="file">待解压文件名(包含物理路径)</param> /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param> public static bool UnpackFiles(string file, string dir) { try { if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } ZipInputStream s = new ZipInputStream(File.OpenRead(file)); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName != String.Empty) { Directory.CreateDirectory(dir + directoryName); } if (fileName != String.Empty) { FileStream streamWriter = File.Create(dir + theEntry.Name); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); return true; } catch (Exception) { throw; } } #endregion #region 私有方法 /// <summary> /// 递归压缩文件夹方法 /// </summary> public static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); s.PutNextEntry(entry); s.Flush(); filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } catch { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return false; } } return res; } /// <summary> /// 压缩目录 /// </summary> /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param> /// <param name="ZipedFile">压缩后的文件名,全路径格式</param> public static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level) { bool res; if (!Directory.Exists(FolderToZip)) { return false; } ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile)); s.SetLevel(level); res = ZipFileDictory(FolderToZip, s, ""); s.Finish(); s.Close(); return res; } /// <summary> /// 压缩文件 /// </summary> /// <param name="FileToZip">要进行压缩的文件名</param> /// <param name="ZipedFile">压缩后生成的压缩文件名</param> public static bool ZipFile(string FileToZip, string ZipedFile, int level) { if (!File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!"); } FileStream ZipFile = null; ZipOutputStream ZipStream = null; ZipEntry ZipEntry = null; bool res = true; try { ZipFile = File.OpenRead(FileToZip); byte[] buffer = new byte[ZipFile.Length]; ZipFile.Read(buffer, 0, buffer.Length); ZipFile.Close(); ZipFile = File.Create(ZipedFile); ZipStream = new ZipOutputStream(ZipFile); ZipEntry = new ZipEntry(Path.GetFileName(FileToZip)); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(level); ZipStream.Write(buffer, 0, buffer.Length); } catch { res = false; } finally { if (ZipEntry != null) { ZipEntry = null; } if (ZipStream != null) { ZipStream.Finish(); ZipStream.Close(); } if (ZipFile != null) { ZipFile.Close(); ZipFile = null; } GC.Collect(); GC.Collect(1); } return res; } #endregion #region ICSharpCode.SharpZipLib开始压缩、解压 /// <summary> /// 压缩 /// </summary> /// <param name="FileToZip">待压缩的文件目录</param> /// <param name="ZipedFile">生成的目标文件</param> /// <param name="level">6</param> public static bool Zip(String FileToZip, String ZipedFile, int level) { if (Directory.Exists(FileToZip)) { return ZipFileDictory(FileToZip, ZipedFile, level); } else if (File.Exists(FileToZip)) { return ZipFile(FileToZip, ZipedFile, level); } else { return false; } } /// <summary> /// 解压 /// </summary> /// <param name="FileToUpZip">待解压的文件</param> /// <param name="ZipedFolder">解压目标存放目录</param> public static void UnZip(string FileToUpZip, string ZipedFolder) { if (!File.Exists(FileToUpZip)) { return; } if (!Directory.Exists(ZipedFolder)) { Directory.CreateDirectory(ZipedFolder); } ZipInputStream s = null; ZipEntry theEntry = null; string fileName; FileStream streamWriter = null; try { s = new ZipInputStream(File.OpenRead(FileToUpZip)); while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.Name != String.Empty) { fileName = Path.Combine(ZipedFolder, theEntry.Name); if (fileName.EndsWith("/") || fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } streamWriter = File.Create(fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } finally { if (streamWriter != null) { streamWriter.Close(); streamWriter = null; } if (theEntry != null) { theEntry = null; } if (s != null) { s.Close(); s = null; } GC.Collect(); GC.Collect(1); } } #endregion #region 使用系统的WinRAR压缩、解压缩 #region 私有变量 String the_rar; RegistryKey the_Reg; Object the_Obj; String the_Info; ProcessStartInfo the_StartInfo; Process the_Process; #endregion /// <summary> /// 压缩 /// </summary> /// <param name="zipname">要解压的文件名</param> /// <param name="zippath">要压缩的文件目录</param> /// <param name="dirpath">初始目录</param> public void EnZip(string zipname, string zippath, string dirpath) { try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " a " + zipname + " " + zippath; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_StartInfo.WorkingDirectory = dirpath; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 解压缩 /// </summary> /// <param name="zipname">要解压的文件名</param> /// <param name="zippath">要解压的文件路径</param> public void DeZip(string zipname, string zippath) { try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " X " + zipname + " " + zippath; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion #endregion }
显示效果:
以上类库内容来源互联网,站长稍作整理
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。