.NET使用ICSharpCode.SharpZipLib压缩/解压文件

时间:2023-03-09 19:49:11
.NET使用ICSharpCode.SharpZipLib压缩/解压文件

SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压

1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下

http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

2.编写工具类ZipUtil,一般放在App_Code文件夹下

 using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
/// <summary>
/// ZipUtil 压缩解压工具
/// </summary>
public class ZipUtil
{
public ZipUtil()
{ }
/// <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>
/// <returns></returns>
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 = ;
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 true;
}
catch (Exception)
{
throw;
}
}
}

3.编写HTML页面

我们上传文件使用FileUpload控件(最大支持20M上传)和一个Button按钮。

 <asp:FileUpload ID="upZip" runat="server" Width="200px" />
<asp:Label ID="lblMsg" runat="server" Text="" ForeColor="blue"></asp:Label>
<asp:Button ID="btn" runat="server" Text="上传" Width="68px" OnClick="btn_Click"/>

4.编写按钮点击事件

我们这里将本地制作好的一个专题压缩成zip文件,上传到服务器上,在对文件进行解压,并删除原来的压缩文件。(确保zip中包好一个根目录文件夹)

 protected void btn_Click(object sender, EventArgs e)
{
//获取上传文件名 demo.zip
string fileName = upZip.FileName;
if (fileName == null || fileName=="")
{
lblMsg.Text = "没有选择文件";
}
else
{
//截取专题目录名 demo
string dirName = fileName.Substring(, fileName.IndexOf('.'));
//获取上传目录 ~/zhuanti/2013/
string updir = "~/zhuanti/" + DateTime.Now.Year + "/";
//获取专题目录 ~/zhuanti/2013/demo/
string ztdir = updir + dirName +"/";
//转换为物理路径 E:\\root\\UI\\zhuanti\\2013\\demo\\
string abZtdir = Server.MapPath(ztdir);
//判断目录是否已经存在
if (Directory.Exists(abZtdir))
{//存在
lblMsg.Text = "专题目录已存在";
}
else
{//不存在
//判断压缩包类型
string lastName = fileName.Substring(fileName.LastIndexOf("."));
if (lastName.ToLower() == ".zip")
{
//上传压缩包完整路径 ~/zhuanti/2013/demo.zip
string fullpath = updir + fileName;
//物理路径 E:\\root\\UI\\zhuanti\\2013\\demo.zip
string abFullPath = Server.MapPath(fullpath);
try
{
//上传目录是否存在
if (!Directory.Exists(Server.MapPath(updir)))
{
Directory.CreateDirectory(Server.MapPath(updir));
}
//上传
this.upZip.SaveAs(Server.MapPath(fullpath));
//解压
ZipUtil.UnpackFiles(abFullPath, Server.MapPath(updir));
//删除压缩包
if (File.Exists(abFullPath))
{
File.Delete(abFullPath);
}
loadFile();
}
catch (Exception ex)
{
lblMsg.Text = "操作失败";
} }
else
{
lblMsg.Text = "只能上传ZIP文件";
}
}
} }

5.编写loadFile()方法,查看文件夹是否上传成功。这里用一个下拉列表控件显示目录下的所有文件夹

HTML代码

 <asp:ListBox ID="lbxFile" runat="server" CausesValidation="True" Rows="" SelectionMode="Multiple" Width="300px"></asp:ListBox>

CS文件代码

  //读取目录文件列表
public void loadFile()
{
      //要读取的目录物理路径
string abdir = Server.MapPath("~/zhuanti/"+DateTime.Now.Year+"/");
      //创建DirectoryInfo对象
DirectoryInfo theDir = new DirectoryInfo(abdir);
      //获取目录下所有子目录
DirectoryInfo[] thisOne = theDir.GetDirectories();
      //获取目录下所有子目录(带路径)
//string[] dirs = Directory.GetDirectories(abdir);
      //下拉框绑定数据
lbxFile.DataSource = thisOne;
lbxFile.DataBind();
}