First.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="First.aspx.cs" Inherits="Compression._Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnYS" runat="server" Text="压缩文件" OnClick="btnYS_Click" />
<asp:Button ID="btnJY" runat="server" Text="解压文件" OnClick="btnJY_Click" />
</div>
</form>
</body>
</html>
First.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace Compression
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnYS_Click(object sender, EventArgs e)
{
string[] FileProperties = new string[2];
FileProperties[0] = "image";//待压缩文件目录
FileProperties[1] = "zip\\des.zip";//压缩后的目标文件
ZipClass Zc = new ZipClass();
Zc.ZipFileMain(FileProperties);
}
protected void btnJY_Click(object sender, EventArgs e)
{
string[] FileProperties = new string[2];
FileProperties[0] = "zip\\des.zip";//待解压的文件
FileProperties[1] = "unzip\\";//解压后放置的目标目录
UnZipClass UnZc = new UnZipClass();
UnZc.UnZip(FileProperties);
}
}
}
ZipClass
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
namespace Compression
{
public class ZipClass
{
public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
{
//如果文件没有找到,则报错
if (!System.IO.File.Exists(FileToZip))
{
throw new System.IO.FileNotFoundException("指定的文件 " + FileToZip + " 没有找到. 压缩被中断了。");
}
System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
ZipEntry ZipEntry = new ZipEntry("ZippedFile");
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(CompressionLevel);
byte[] buffer = new byte[BlockSize];
System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, size);
try
{
while (size < StreamToZip.Length)
{
int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
catch (System.Exception ex)
{
throw ex;
}
ZipStream.Finish();
ZipStream.Close();
StreamToZip.Close();
}
public void ZipFileMain(string[] args)
{
//string[] filenames = Directory.GetFiles(args[0]);
string srcUrl = HttpRuntime.AppDomainAppPath.ToString() + args[0];
string[] filenames = Directory.GetFiles(srcUrl);
Crc32 crc = new Crc32();
ZipOutputStream s = new ZipOutputStream(File.Create(HttpRuntime.AppDomainAppPath.ToString() + args[1]));
s.SetLevel(6); // 0 - 仅存储 到 9 - 表示最佳压缩
foreach (string file in filenames)
{
//打开压缩文件
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(Path.GetFileName(file)); //文件名,创建条目
entry.DateTime = DateTime.Now;
//设置大小和crc,因为有关大小和crc的信息应该存储在header中,如果没有设置它会自动写入footer。
//(在这种情况下,header中的size == crc == -1)某些ZIP程序的zip文件存在问题,这些文件不会在header中存储大小和crc。
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
s.Finish();
s.Close();
}
}
}
UnZipClass.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Zip;
namespace Compression
{
public class UnZipClass
{
public void UnZip(string[] args)
{
string srcUrl = HttpRuntime.AppDomainAppPath.ToString() + args[0];
string unzipUrl = HttpRuntime.AppDomainAppPath.ToString() + args[1];
ZipInputStream s = new ZipInputStream(File.OpenRead(srcUrl));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(HttpRuntime.AppDomainAppPath.ToString() + args[1]);
string fileName = Path.GetFileName(theEntry.Name);
//生成解压目录
Directory.CreateDirectory(directoryName); // + "/" + theEntry.Name.Substring(17)
if (fileName != String.Empty)
{
//解压文件到指定的目录
FileStream streamWriter = File.Create(unzipUrl + 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();
}
}
}
运行结果如图:
image是待压缩的图片的文件夹
zip是压缩路径
unzip是解压路径
C#实现文件的压缩和解压缩
在C#中实现文件的压缩和解压缩,需要使用第三方的组建完成。常用的是:SharpZipLib
组件。
- 1、压缩和解压缩有两种典型的算法,一种是
BZIP2
算法,另一种是GZIP
算法。BZIP2
能够获得较高的压缩比,但是压缩和解压缩比较耗时,GZIP
效率比较高,但是压缩比较低。 - 2、
BZIP2
压缩算法的相关类,位于命名空间:ICSharpCode.SharpZipLib.BZip2
中,算法要求指定输入流和输出流,并指定压缩方法使用的块大小,一般为2048
. - 3、
GZIP
压缩算法的相关类,位于命名空间:ICSharpCode.SharpZipLib.GZip
中,首先创建GZipOutputStream
类实例,作为压缩文件的输出流,使用GZipOutputStream
类实例的Write
方法,将从源文件读取的数据写入输入流。同时完成压缩运算。 - 4、使用实例:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CP._Default" %>
<!DOCTYPE html">
<html>
<head>
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnZip" runat="server" Text="开始压缩" OnClick="btnZip_Click" />
<hr />
<asp:Button ID="btnUnzip" runat="server" Text="开始解压" OnClick="btnUnzip_Click" />
<br />
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
namespace C_实现文件的压缩和解压缩
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnZip_Click(object sender, EventArgs e)
{
string srcFile = Server.MapPath("~/图片/0102583.png");//准备压缩的文件名
string zipFile = Server.MapPath("~/zip/test");//压缩后的文件名
string unzipFile = Server.MapPath("~/unzip/result.png");//解压后的文件名
ZipAndUnzipFile context = new ZipAndUnzipFile();
context.StartZip(srcFile, zipFile, unzipFile);
}
protected void btnUnzip_Click(object sender, EventArgs e)
{
string zipFile = Server.MapPath("~/zip/test");//压缩后的文件名
string unzipFile = Server.MapPath("~/unzip/result.png");//解压后的文件名
string unzipFile2 = Server.MapPath("~/unzip/result2.png");//解压后的文件名2
ZipAndUnzipFile context = new ZipAndUnzipFile();
context.StartUnzip(zipFile, unzipFile, unzipFile2);
}
}
}
ZipAndUnzipFile.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip;
namespace C_实现文件的压缩和解压缩
{
public class ZipAndUnzipFile : Page
{
public void StartZip(string srcFile, string zipFile, string unzipFile)
{
HttpContext.Current.Response.Write("使用BZIP开始压缩文件……<br/>");
if (BZipFile(srcFile, zipFile + ".bz"))
{
HttpContext.Current.Response.Write("文件压缩完成<br/>");
}
else
{
HttpContext.Current.Response.Write("文件压缩失败<br/>");
}
HttpContext.Current.Response.Write("使用GZIP开始压缩文件……<br/>");
if (GZipFile(srcFile, zipFile + ".gz"))
{
HttpContext.Current.Response.Write("文件压缩完成<br/>");
}
else
{
HttpContext.Current.Response.Write("文件压缩失败<br/>");
}
}
public void StartUnzip(string zipFile, params string[] unzipFileArray)
{
HttpContext.Current.Response.Write("使用BZIP开始解压文件……<br/>");
if (UnBzipFile(zipFile + ".bz", unzipFileArray[0]))
{
HttpContext.Current.Response.Write("文件解压完成<br/>");
}
else
{
HttpContext.Current.Response.Write("文件解压失败<br/>");
}
HttpContext.Current.Response.Write("使用GZIP开始解压文件……<br/>");
if (UnGzipFile(zipFile + ".gz", unzipFileArray[1]))
{
HttpContext.Current.Response.Write("文件解压完成<br/>");
}
else
{
HttpContext.Current.Response.Write("文件解压失败<br/>");
}
}
//使用BZIP压缩文件的方法
public bool BZipFile(string sourcefilename, string zipfilename)
{
bool blResult;//表示压缩是否成功的返回结果
//为源文件创建文件流实例,作为压缩方法的输入流参数
FileStream srcFile = File.OpenRead(sourcefilename);
//为压缩文件创建文件流实例,作为压缩方法的输出流参数
FileStream zipFile = File.Open(zipfilename, FileMode.Create);
try
{
//以4096字节作为一个块的方式压缩文件
BZip2.Compress(srcFile, zipFile, 4096);
blResult = true;
}
catch (Exception ee)
{
HttpContext.Current.Response.Write(ee.Message);
blResult = false;
}
srcFile.Close();//关闭源文件流
zipFile.Close();//关闭压缩文件流
return blResult;
}
//使用BZIP解压文件的方法
public bool UnBzipFile(string zipfilename, string unzipfilename)
{
bool blResult;//表示解压是否成功的返回结果
//为压缩文件创建文件流实例,作为解压方法的输入流参数
FileStream zipFile = File.OpenRead(zipfilename);
//为目标文件创建文件流实例,作为解压方法的输出流参数
FileStream destFile = File.Open(unzipfilename, FileMode.Create);
try
{
BZip2.Decompress(zipFile, destFile);//解压文件
blResult = true;
}
catch (Exception ee)
{
HttpContext.Current.Response.Write(ee.Message);
blResult = false;
}
destFile.Close();//关闭目标文件流
zipFile.Close();//关闭压缩文件流
return blResult;
}
//使用GZIP压缩文件的方法
public bool GZipFile(string sourcefilename, string zipfilename)
{
bool blResult;//表示压缩是否成功的返回结果
//为源文件创建读取文件的流实例
FileStream srcFile = File.OpenRead(sourcefilename);
//为压缩文件创建写入文件的流实例,
GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename, FileMode.Create));
try
{
byte[] FileData = new byte[srcFile.Length];//创建缓冲数据
srcFile.Read(FileData, 0, (int)srcFile.Length);//读取源文件
zipFile.Write(FileData, 0, FileData.Length);//写入压缩文件
blResult = true;
}
catch (Exception ee)
{
HttpContext.Current.Response.Write(ee.Message);
blResult = false;
}
srcFile.Close();//关闭源文件
zipFile.Close();//关闭压缩文件
return blResult;
}
//使用GZIP解压文件的方法
public bool UnGzipFile(string zipfilename, string unzipfilename)
{
bool blResult;//表示解压是否成功的返回结果
//创建压缩文件的输入流实例
GZipInputStream zipFile = new GZipInputStream(File.OpenRead(zipfilename));
//创建目标文件的流
FileStream destFile = File.Open(unzipfilename, FileMode.Create);
try
{
int buffersize = 2048;//缓冲区的尺寸,一般是2048的倍数
byte[] FileData = new byte[buffersize];//创建缓冲数据
while (buffersize > 0)//一直读取到文件末尾
{
buffersize = zipFile.Read(FileData, 0, buffersize);//读取压缩文件数据
destFile.Write(FileData, 0, buffersize);//写入目标文件
}
blResult = true;
}
catch (Exception ee)
{
HttpContext.Current.Response.Write(ee.Message);
blResult = false;
}
destFile.Close();//关闭目标文件
zipFile.Close();//关闭压缩文件
return blResult;
}
}
}