技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營(yíng)

贊助商

分類目錄

贊助商

最新文章

搜索

簡(jiǎn)單易用!asp.net用DotNetZip壓縮文件,Ionic.Zip.dll下載

作者:admin    時(shí)間:2022-8-24 12:45:42    瀏覽:

在本文中,我們將通過示例和示例代碼探討如何使用 C# 在 ASP.NET 中創(chuàng)建 Zip 文件。

在本文示例中,會(huì)使用到Ionic.Zip.dll ,本文將提供該文件的下載,用戶下載后放到網(wǎng)站的bin目錄下即可直接使用。

DotNetZip 介紹

首先說明的是,DotNetZip 是一個(gè)小型、易于使用的類庫,用于處理 .zip 文件。它可以啟用以 VB.NET、C# 或任何 .NET 語言編寫的 .NET 應(yīng)用程序,以輕松創(chuàng)建、讀取和更新 zip 文件。使用 DotNetZip 可以輕松進(jìn)行 Zip 壓縮。

DotNetZip 打包為單個(gè) DLL,即為 Ionic.Zip.dll,大小約為 400k。它沒有第三方依賴項(xiàng)。它是中等信任,因此可以在大多數(shù)主機(jī)上使用。僅通過引用 DLL 來獲取壓縮。

適用條件

Ionic.Zip.dll文件適用.NET 2.0以上版本。

命名空間

我們將需要使用以下命名空間。

using System.IO;
using Ionic.Zip;

多個(gè)實(shí)例(C#)

壓縮單個(gè)文件

string filePath = Server.MapPath("Report.doc");//文件所在位置
using (Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile())
{
//zf.AddFile(filePath, "files");  //"files"是壓縮文件存放的文件夾名稱,會(huì)自動(dòng)生成
zf.AddFile(filePath, "");
zf.Save(Server.MapPath("Report.rar"));//文件保存的地址
}

壓縮多個(gè)文件

using (ZipFile zip = new ZipFile("MyZipFile.zip")
{
  zip.AddFile("c:\\images\\personal\\7440-N49th.png");
  zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf");
  zip.AddFile("ReadMe.txt");
  zip.Save();
}

壓縮并下載

string filePath = Server.MapPath("Report.doc");//文件所在位置
var fs = Response.OutputStream;
using (Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile())
{
//zf.AddFile(filePath, "files");  //"files"是壓縮文件存放的文件夾名稱,會(huì)自動(dòng)生成
zf.AddFile(filePath, "");  // 第二個(gè)參數(shù)是文件夾名稱,留空表示當(dāng)前位置
zf.Save(fs);//保存到輸出流
}
string fileName = "Report.rar"; //下載顯示的文件名字
        
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.Flush();
Response.End();

壓縮文件夾,適合壓縮多個(gè)文件

string pathname = Server.MapPath("~/files/");
string[] filename = Directory.GetFiles(pathname);
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
  zip.AddFiles(filename, "files");
  zip.Save(Server.MapPath("~/files.rar"));
}

解壓

string zipToUnpack = Server.MapPath("~/files.zip");  // 不能解壓rar文件
string unpackDirectory = Server.MapPath("~/files/");
using (ZipFile zip1 = ZipFile.Read(zipToUnpack))
{
foreach (ZipEntry ex in zip1)
{
ex.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}

遺憾的是,該DLL不能解壓rar文件,它只能解壓zip文件,不過它卻能把文件壓縮為rar文件。

總結(jié)

本文介紹了asp.net如何使用DotNetZip Ionic.Zip.dll壓縮文件,該方法代碼簡(jiǎn)單易用,推薦使用。

如果你不想引用第三方類庫來壓縮文件,那么如果你使用的是.NET4.5版本以上,你可以用ZipArchive、ZipFile等類來實(shí)現(xiàn)壓縮和解壓。

Ionic.Zip.dll 文件下載

Ionic.Zip.dll.rar

標(biāo)簽: 壓縮文件  Ionic.Zip.dll  asp.net  
x
  • 站長(zhǎng)推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */