ASP.Net MVC——DotNetZip簡單使用,解決文件壓縮問題。


准備工作:

 在vs工具欄中找到NuGet

 

下載DotNetZip

現在就可以使用DotNetZip強大的類庫了,在這里我給出一些簡單的使用。

    public ActionResult Export()
        {
            using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))
            {
                zip.AddFile(Server.MapPath("~/Img/2.png"), "Images");
                zip.AddFile(Server.MapPath("~/File/1.pdf"), "Files");
                zip.Save(Server.MapPath("~/ZIP/Test.zip"));
                return File(Server.MapPath("~/ZIP/Test.zip"),
                                           "application/zip", "sample.zip");
            }
        }

 

 

其中“System.Text.Encoding.Default”是解決中文亂碼問題。

從字面上就可以理解zip.AddFile就是從指定路徑把文件加入到zip中,后面的參數“Images"和“Files”就是說解壓后看到了兩個目錄。

zip.Sava就是保存zip文件到某個目錄。

 解壓后    

要是文件都在一個目錄的話還可以這樣:

  public ActionResult Export()
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(Server.MapPath("~/Img/"));
                zip.Save(Server.MapPath("~/ZIP/Test.zip"));
                return File(Server.MapPath("~/ZIP/Test.zip"),
                                           "application/zip", "sample.zip");
            }
        }

 

下面是加密:

 public ActionResult Export()
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.Password="123";
                zip.AddDirectory(Server.MapPath("~/Img/"));
                zip.Save(Server.MapPath("~/ZIP/Test.zip"));
                return File(Server.MapPath("~/ZIP/Test.zip"),
                                           "application/zip", "sample.zip");
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM