c# 用ICSharpCode組件壓縮文件
一、單文件壓縮
場景,文件可能比較大,需要壓縮傳輸,比如上傳和下載
/// <summary> /// 單文件壓縮 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="zipedFile">zip壓縮文件</param> /// <param name="blockSize">緩沖區大小</param> /// <param name="compressionLevel">壓縮級別</param> public static void ZipFile(string sourceFile, string zipedFile, int blockSize = 1024, int compressionLevel = 6) { if (!File.Exists(sourceFile)) { throw new System.IO.FileNotFoundException("The specified file " + sourceFile + " could not be found."); } var fileName = System.IO.Path.GetFileNameWithoutExtension(sourceFile); FileStream streamToZip = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); FileStream zipFile = File.Create(zipedFile); ZipOutputStream zipStream = new ZipOutputStream(zipFile); ZipEntry zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); //存儲、最快、較快、標準、較好、最好 0-9 zipStream.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int size = streamToZip.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, size); try { while (size < streamToZip.Length) { int sizeRead = streamToZip.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sizeRead); size += sizeRead; } } catch (Exception ex) { throw ex; } zipStream.Finish(); zipStream.Close(); streamToZip.Close(); }
說明:26行,blocksize為緩存區大小,不能設置太大,如果太大也會報異常。26-38行,把文件通過FileStream流,讀取到緩沖區中,再寫入到ZipOutputStream流。你可以想象,兩個管道,一個讀,另一個寫,中間是緩沖區,它們的工作方式是同步的方式。想一下,能不能以異步的方式工作,讀的管道隻管讀,寫的管道隻管寫?如果是這樣一個場景,讀的特別快,寫的比較慢,比如,不是本地寫,而是要經過網絡傳輸,就可以考慮異步的方式。怎麼做,讀者可以自行改造。關鍵一點,流是有順序的,所以要保證順序的正確性即可。
二、多文件壓縮
這種場景也是比較多見,和單文件壓縮類似,無非就是多循環幾次。
/// <summary> /// 多文件壓縮 /// </summary> /// <param name="zipfile">zip壓縮文件</param> /// <param name="filenames">源文件集合</param> /// <param name="password">壓縮加密</param> public void ZipFiles(string zipfile, string[] filenames, string password = "") { ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(zipfile)); s.SetLevel(6); if (password != "") s.Password = Md5Help.Encrypt(password); foreach (string file in filenames) { //打開壓縮文件 FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); var name = Path.GetFileName(file); ZipEntry entry = new ZipEntry(name); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); }
說明:21行,緩沖區大小直接為文件大小,所以一次讀完,沒有循環讀寫。這種情況下,單個文件不能太大,比如超過1G。14行,可以為壓縮包設置密碼,MD5的生成方法如下:
public class Md5Help { /// <summary> ///32位 MD5加密 /// </summary> /// <param name="str">加密字符</param> /// <returns></returns> public static string Encrypt(string str) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] encryptdata = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); return Convert.ToBase64String(encryptdata); } }
三、多文件異步壓縮
上面同步的壓縮的前提是,假設文件不大,而且文件數不多,但是現實是,不光文件大,而且文件數比較多。這種情況,就要考慮異步方法瞭。否則會阻塞主線程,就是我們平常說的卡死。
/// <summary> /// 異步壓縮文件為zip壓縮包 /// </summary> /// <param name="zipfile">壓縮包存儲路徑</param> /// <param name="filenames">文件集合</param> public static async void ZipFilesAsync(string zipfile, string[] filenames) { await Task.Run(() => { ZipOutputStream s = null; try { s = new ZipOutputStream(System.IO.File.Create(zipfile)); s.SetLevel(6); // 0 - store only to 9 - means best compression foreach (string file in filenames) { //打開壓縮文件 FileStream fs = System.IO.File.OpenRead(file); var name = Path.GetFileName(file); ZipEntry entry = new ZipEntry(name); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); //如果文件大於1G long blockSize = 51200; var size = (int)fs.Length; var oneG = 1024 * 1024 * 1024; if (size > oneG) { blockSize = oneG; } byte[] buffer = new byte[blockSize]; size = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, size); while (size < fs.Length) { int sizeRead = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sizeRead); size += sizeRead; } s.Flush(); fs.Close(); } } catch (Exception ex) { Console.WriteLine("異步壓縮文件出錯:" + ex.Message); } finally { s?.Finish(); s?.Close(); } }); }
四、壓縮文件夾
實際的應用當中,是文件和文件夾一起壓縮,所以這種情況,就幹脆把要壓縮的東西全部放到一個文件夾,然後進行壓縮。
主方法如下:
/// <summary> /// 異步壓縮文件夾為zip壓縮包 /// </summary> /// <param name="zipfile">壓縮包存儲路徑</param> /// <param name="sourceFolder">壓縮包存儲路徑</param> /// <param name="filenames">文件集合</param> public static async void ZipFolderAsync(string zipfile, string sourceFolder, string[] filenames) { await Task.Run(() => { ZipOutputStream s = null; try { s = new ZipOutputStream(System.IO.File.Create(zipfile)); s.SetLevel(6); // 0 - store only to 9 - means best compression CompressFolder(sourceFolder, s, sourceFolder); } catch (Exception ex) { Console.WriteLine("異步壓縮文件出錯:" + ex.Message); } finally { s?.Finish(); s?.Close(); } }); }
壓縮的核心方法:
/// <summary> /// 壓縮文件夾 /// </summary> /// <param name="source">源目錄</param> /// <param name="s">ZipOutputStream對象</param> /// <param name="parentPath">和source相同</param> public static void CompressFolder(string source, ZipOutputStream s, string parentPath) { string[] filenames = Directory.GetFileSystemEntries(source); foreach (string file in filenames) { if (Directory.Exists(file)) { CompressFolder(file, s, parentPath); //遞歸壓縮子文件夾 } else { using (FileStream fs = System.IO.File.OpenRead(file)) { var writeFilePath = file.Replace(parentPath, ""); ZipEntry entry = new ZipEntry(writeFilePath); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); //如果文件大於1G long blockSize = 51200; var size = (int)fs.Length; var oneG = 1024 * 1024 * 1024; if (size > oneG) { blockSize = oneG; } byte[] buffer = new byte[blockSize]; size = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, size); while (size < fs.Length) { int sizeRead = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sizeRead); size += sizeRead; } s.Flush(); //清除流的緩沖區,使得所有緩沖數據都寫入到文件中 fs.Close(); } } } }
唯一需要註意的地方,可能解壓出來的目錄結構和壓縮前的文件目錄不同,這時候檢查parentPath參數,它在ZipEntry實體new的時候用,替換絕對路徑為當前的相對路徑,也就是相對壓縮文件夾的路徑。
上面的方法比較復雜,還有一種相對簡單的方式,直接調用api:
public static string ZipFolder(string sourceFolder, string zipFile) { string result = ""; try { //創建壓縮包 if (!Directory.Exists(sourceFolder)) return result = "壓縮文件夾不存在"; DirectoryInfo d = new DirectoryInfo(sourceFolder); var files = d.GetFiles(); if (files.Length == 0) { //找子目錄 var ds = d.GetDirectories(); if (ds.Length > 0) { files = ds[0].GetFiles(); } } if (files.Length == 0) return result = "待壓縮文件為空"; System.IO.Compression.ZipFile.CreateFromDirectory(sourceFolder, zipFile); } catch (Exception ex) { result += "壓縮出錯:" + ex.Message; } return result; }
以上就是c# 用ICSharpCode組件壓縮文件的詳細內容,更多關於c# 壓縮文件的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- C#實現多文件打包壓縮(.Net Core)
- .Net Core 多文件打包壓縮的實現代碼
- Java實現把文件壓縮成zip文件的示例代碼
- 手把手教你用SpringBoot將文件打包成zip存放或導出
- Java實現創建Zip壓縮包並寫入文件