.NET 4.5 中新提供的壓縮類

來源:互聯網
上載者:User

標籤:方法   ons   存在   2.4   code   檢查   div   方便   tin   

Windows8 的開發已經如火如荼開始了,在 Windows8 中提供的 .NET Framework 已經更新到了 4.5 版,其中又增加了一些新的特性,對壓縮檔的支援就是其中之一。

在 4.5 之前,處理壓縮檔,我們經常需要使用第三方的類庫 SharpZipLib, 現在可以直接實現了。

1.準備工作

首先做一下準備工作,需要確保你使用 .NET 4.5 版,可以在項目的屬性視窗中檢查一下。

然後,引用必須的程式集。

程式集有兩個:System.IO.Compression 和 System.IO.Compression.FileSystem.

類似於對檔案和目錄的操作,對於壓縮檔也提供了兩種方式:ZipArchive 和 ZipFile,分別對應兩個新增加的類 ZipArchive 和 ZipFile。這兩個類都定義在命名空間 System.IO.Compression 中。

為了後面示範方便,我們定義一個表示壓縮檔路徑的常量。

const string zipFilePath = @"..\..\Sample.zip";
2. 使用 ZipArchive

先看ZipArchive的使用。

2.1 建立壓縮檔

建立一個空的壓縮檔,使用 ZipArchiveMode.Create 建立參數。

// 建立 Zip 檔案using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create))using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create)){}

使用 WinRaR 開啟壓縮檔,可以看到裡面沒有檔案。

2.2 建立並添加檔案

通常,在建立的同時,我們就會加入一些檔案,下面的例子中,我們將當前的執行程式檔案本身加到壓縮檔中。

// 建立並添加被壓縮檔using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create))using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create)){    System.Reflection.Assembly assemble = System.Reflection.Assembly.GetExecutingAssembly();    string path = assemble.Location;    string filename = System.IO.Path.GetFileName(path);    ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);    using (System.IO.Stream stream = readMeEntry.Open())    {        byte[] bytes = System.IO.File.ReadAllBytes(path);        stream.Write(bytes, 0, bytes.Length);    }}

現在,開啟壓縮檔,可以看到檔案已經被壓縮排來了。

2.3 列出壓縮檔內容

當然,也可以通過程式檢查壓縮檔的內容了。使用 Read 方式就可以了。

// 列出壓縮壓縮檔using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)){    foreach (var zipArchiveEntry in archive.Entries)        Console.WriteLine(            "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName        );}
2.4 提取壓縮檔

當然可以從壓縮檔中提取被壓縮的內容了。

// 讀取其中一個檔案的內容using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)){    // 解壓某個檔案    ZipArchiveEntry entry = archive.GetEntry("ZipArchiveSample.exe");    Console.WriteLine(entry.Name);    using (System.IO.Stream stream = entry.Open())    {        System.IO.Stream output = new FileStream("http://www.cnblogs.com/ZipArchiveSample.exe", FileMode.Create);        int b = -1;        while ((b = stream.ReadByte()) != -1)        {            output.WriteByte((byte) b);        }        output.Close();    }}
2.5 更新壓縮檔

在壓縮檔已經建立之後,還可以開啟它,繼續添加檔案,這就稱為更新了,使用 Update 模式。

// 向現有的壓縮檔中添加檔案using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update)){    // 這裡添加當前正在執行的程式檔案本身    System.Reflection.Assembly assemble = System.Reflection.Assembly.GetExecutingAssembly();    string path = assemble.Location;    string filename = System.IO.Path.GetFileName( path);    ZipArchiveEntry readMeEntry = archive.CreateEntry( filename );    using (System.IO.Stream stream = readMeEntry.Open() )    {        byte[] bytes = System.IO.File.ReadAllBytes(path);        stream.Write(bytes, 0, bytes.Length);    }    foreach (var zipArchiveEntry in archive.Entries)        Console.WriteLine(            "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName        );}            

現在壓縮檔中又增加了一個,這可以一個怪異的檔案,同一個檔案被在壓縮檔中添加了兩次!

3. 使用 ZipFile

除了上邊的基本方法之外,還有一些簡單的使用方法。這涉及到另外一個類:ZipFile。

3.1 建立空壓縮檔
// 刪除壓縮檔System.IO.File.Delete(zipFilePath);// 使用 ZipFile 的靜態方法建立壓縮檔,要保證檔案沒有存在using (ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)){}
3.2 建立並添加檔案

直接添加一個檔案的方法。直接使用 CreateEntryFromFile 就可以了。

System.IO.File.Delete(zipFilePath);// 使用 CreateEntryFromFile 方法添加檔案// 使用 ZipFile 的靜態方法建立壓縮檔using (ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)){    System.Reflection.Assembly assemble = System.Reflection.Assembly.GetExecutingAssembly();    string path = assemble.Location;    string filename = System.IO.Path.GetFileName(path);    zipArchive.CreateEntryFromFile(path, filename);}
3.3 解壓檔案

將壓縮檔解壓到指定的目錄中。

// 解壓檔案ZipFile.ExtractToDirectory(zipFilePath, "../..");
3.4 壓縮一個目錄

還可以直接將一個目錄中所有的檔案都壓縮到一個壓縮檔中。

// 壓縮指定目錄中所有檔案System.IO.File.Delete(zipFilePath);ZipFile.CreateFromDirectory(".", zipFilePath);

你是不是最喜歡這個方法?現在壓縮檔中的檔案更多了。

附錄:

SharpZipLib 的: http://www.icsharpcode.net/OpenSource/SharpZipLib/

.NET 4.5 中新提供的壓縮類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.