Windows 8開發 WinRT 對ZIP檔案解壓縮及檔案夾的ZIP壓縮

來源:互聯網
上載者:User

在開發一個Win8 Modern UI APP時,如果需要用到ZIP壓縮和解壓檔案(注意不是GZIP),可能會首先想到使用SharpZipLib,由於我們在WP7的時候就使用的這個類庫。不過,隨著WIN8開始使用.Net 4.5和C# 5.0,引入了一個新功能,其實ZIP壓縮與解壓縮已經可以不用第三方類庫就能實現了。

  主要需要用到System.IO.Compression命名空間。下面示範程式需要用到的全部命名空間如下:

using System;using System.Collections.Generic;using System.IO;using System.IO.Compression;using System.Runtime.InteropServices.WindowsRuntime;using System.Threading.Tasks;using Windows.Storage;using Windows.Storage.Streams;

  對zip檔案的解壓縮操作:

public async Task<StorageFolder> UnZipFile(string folderName, byte[] data)        {            StorageFolder unZipfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);            var stream = new MemoryStream(data);            var zipArchive = new ZipArchive(stream, ZipArchiveMode.Read);            foreach (var zipArchiveEntry in zipArchive.Entries)            {                if (!String.IsNullOrEmpty(zipArchiveEntry.FullName))                {                    if (!zipArchiveEntry.FullName.EndsWith("/"))                    {                        string fileName = zipArchiveEntry.FullName.Replace("/", "\\");                        using (Stream fileData = zipArchiveEntry.Open())                        {                            StorageFile newFile = await unZipfolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);                            using (IRandomAccessStream newFileStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))                            {                                using (Stream s = newFileStream.AsStreamForWrite())                                {                                    await fileData.CopyToAsync(s);                                    await s.FlushAsync();                                    s.Dispose();                                }                                newFileStream.Dispose();                            }                        }                    }                }            }            return unZipfolder;        }

  UnZipFile()方法,傳入的第一個參數為欲解壓的檔案位置(解壓縮位置LocalFolder中建立一個檔案夾,可以根據實際需求進行修改),第二個參數為壓縮檔的位元組數組,這個數組可能來源於網路下載或者其他隔離儲存區 (Isolated Storage)空間中的檔案。

  對檔案夾的壓縮(如果需要壓縮單個檔案,代碼可從下面的代碼中提取):

        public async Task<byte[]> ZipFolder(StorageFolder folder)        {            using (var zipMemoryStream = new MemoryStream())            {                using (var zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Create))                {                    await AddZipFolderToEntry(zipArchive, folder, "");                }                return zipMemoryStream.ToArray();            }        }        private async Task<bool> AddZipFolderToEntry(ZipArchive zipArchive, StorageFolder folder, string entryFirst)        {            IReadOnlyList<StorageFile> filesToCompress = await folder.GetFilesAsync();            foreach (StorageFile fileToCompress in filesToCompress)            {                byte[] buffer = (await FileIO.ReadBufferAsync(fileToCompress)).ToArray();                ZipArchiveEntry entry = zipArchive.CreateEntry(entryFirst + fileToCompress.Name);                using (Stream entryStream = entry.Open())                {                    await entryStream.WriteAsync(buffer, 0, buffer.Length);                }            }            var childrenFolder = await folder.GetFoldersAsync();            foreach (var storageFolder in childrenFolder)            {                await AddZipFolderToEntry(zipArchive, storageFolder, entryFirst + storageFolder.Name + "/");            }            return true;        }

  ZipFolder()方法為將一個檔案夾極其子檔案夾與檔案壓縮成一個ZIP檔案,具體過程為遞迴調用AddZipFolderToEntry。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.