C#压缩与解压

时间:2022-04-14 08:47:10
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Runtime.InteropServices;
namespace Common
{
/// <summary>
/// Zip壓縮與解壓縮
/// </summary>
public class ZipHelper
{
/// <summary>
/// 壓縮單個文件
/// </summary>
/// <param name="fileToZip">要進行壓縮的文件名</param>
/// <param name="zipedFile">壓縮后生成的壓縮文件名</param>
public static void ZipFile(string fileToZip, string zipedFile)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new System.IO.FileNotFoundException("指定要壓縮的文件: " + fileToZip + " 不存在!");
}
using (FileStream fs = File.OpenRead(fileToZip))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
fs.Close();
using (FileStream ZipFile = File.Create(zipedFile))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + );
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel();
ZipStream.Write(buffer, , buffer.Length);
ZipStream.Finish();
ZipStream.Close();
}
}
}
} /// <summary>
/// 壓縮多層目錄
/// </summary>
/// <param name="strDirectory">要進行壓縮的文件夾</param>
/// <param name="zipedFile">壓縮后生成的壓縮文件名</param>
public static void ZipFileDirectory(string strDirectory, string zipedFile)
{
using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile))
{
using (ZipOutputStream s = new ZipOutputStream(ZipFile))
{
ZipSetp(strDirectory, s, "");
}
}
} /// <summary>
/// 遞歸遍歷目錄
/// </summary>
/// <param name="strDirectory">要進行壓縮的文件夾</param>
/// <param name="s">The ZipOutputStream Object.</param>
/// <param name="parentPath">The parent path.</param>
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
{
if (strDirectory[strDirectory.Length - ] != Path.DirectorySeparatorChar)
{
strDirectory += Path.DirectorySeparatorChar;
}
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strDirectory);
foreach (string file in filenames)// 遍历所有的文件和目录
{
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string pPath = parentPath;
pPath += file.Substring(file.LastIndexOf("\\") + );
pPath += "\\";
ZipSetp(file, s, pPath);
}
else // 否则直接压缩文件
{
//打开压缩文件
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + );
ZipEntry entry = new ZipEntry(fileName);
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, , buffer.Length);
}
}
}
} /// <summary>
/// 解压文件
/// </summary>
/// <param name="TargetFile">目标文件</param>
/// <param name="fileDir">解压到指定目录</param>
/// <returns>空字符串,表示解压成功</returns>
public static string unZipFile(string TargetFile, string fileDir)
{
string rootFile = " ";
try
{
//读取压缩文件(zip文件),准备解压缩
ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
ZipEntry theEntry;
string path = fileDir;
//解压出来的文件保存的路径 string rootDir = " ";
//根目录下的第一个子文件夹的名称
while ((theEntry = s.GetNextEntry()) != null)
{
rootDir = Path.GetDirectoryName(theEntry.Name);
//得到根目录下的第一级子文件夹的名称
if (rootDir.IndexOf("\\") >= )
{
rootDir = rootDir.Substring(, rootDir.IndexOf("\\") + );
}
string dir = Path.GetDirectoryName(theEntry.Name);
//根目录下的第一级子文件夹的下的文件夹的名称
string fileName = Path.GetFileName(theEntry.Name);
//根目录下的文件名称
if (dir != " ")
//创建根目录下的子文件夹,不限制级别
{
if (!Directory.Exists(fileDir + "\\" + dir))
{
path = fileDir + "\\" + dir;
//在指定的路径创建文件夹
Directory.CreateDirectory(path);
}
}
else if (dir == " " && fileName != "")
//根目录下的文件
{
path = fileDir;
rootFile = fileName;
}
else if (dir != " " && fileName != "")
//根目录下的第一级子文件夹下的文件
{
if (dir.IndexOf("\\") > )
//指定文件保存的路径
{
path = fileDir + "\\" + dir;
}
} if (dir == rootDir)
//判断是不是需要保存在根目录下的文件
{
path = fileDir + "\\" + rootDir;
} //以下为解压缩zip文件的基本步骤
//基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(path + "\\" + fileName); int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
} streamWriter.Close();
}
}
s.Close(); return rootFile;
}
catch (Exception ex)
{
return "1; " + ex.Message;
}
}
}
}

以上代码,直接复制黏贴,即可使用,但是得下载一个C#的zip程序集,网上到处有,随便下载一个都行:ICSharpCode.SharpZipLib.dll

压缩的调用代码(这是压缩文件夹):

ZipHelper.ZipFileDirectory(Server.MapPath(要压缩的文件夹路径), Server.MapPath("要压缩到的文件夹路径.zip"));//这里目标路径要包含后缀名

解压的调用代码:

 ZipHelper.unZipFile(要解压的压缩文件的路径, Server.MapPath("要解压到什么位置"));//第二个参数是文件夹的路径