您好,登錄后才能下訂單哦!
這篇文章主要講解了“c#怎么用ICSharpCode組件壓縮文件”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“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#怎么用ICSharpCode組件壓縮文件這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。