如何使用 C# 压缩单个文件?
咨詢區
user3362735
我的項目有一個需求,需要對 文件夾 下的文件進行壓縮,我用 ZipFile.CreateFromDirectory 方法發現并不能成功,但我對整個文件夾壓縮是沒有問題的,請問我該如何正確實現?
回答區
John Koerner
可以借助 file 或者 memorystream 再通過 CreateEntryFromFile() 創建一個存檔文件。
filestream
如果你有權限創建一個 zip 文件,那么可以使用 filestream,參考如下代碼:
using?(FileStream?fs?=?new?FileStream(@"C:\Temp\output.zip",FileMode.Create)) using?(ZipArchive?arch?=?new?ZipArchive(fs,?ZipArchiveMode.Create)) {arch.CreateEntryFromFile(@"C:\Temp\data.xml",?"data.xml"); }memorystream
如果你不想保存任何磁盤痕跡,可以在內存中做任何事情,參考如下代碼:
using?(MemoryStream?ms?=?new?MemoryStream()) using?(ZipArchive?arch?=?new?ZipArchive(ms,?ZipArchiveMode.Create)) {arch.CreateEntryFromFile(@"C:\Temp\data.xml",?"data.xml"); }最后你可以將 MemoryStream 寫入到 File 。
using?(FileStream?file?=?new?FileStream("file.bin",?FileMode.Create,?System.IO.FileAccess.Write))?{byte[]?bytes?=?new?byte[ms.Length];ms.Read(bytes,?0,?(int)ms.Length);file.Write(bytes,?0,?bytes.Length);ms.Close(); }John Koerner
其實在 .NET 中有很多種途徑可以解決這種問題,你可以借助一些第三方類,比如:SharpZipLib ,sevenzipsharp, DotNetZip。
當然你用 ZipFile 也是可以解決的,下面是使用 FileStream 的方式。
using?(var?zip?=?ZipFile.Open("file.zip",?ZipArchiveMode.Create)) {var?entry?=?zip.CreateEntry("file.txt");entry.LastWriteTime?=?DateTimeOffset.Now;using?(var?stream=?File.OpenRead(@"c:\path\to\file.txt"))using?(var?entryStream?=?entry.Open())stream.CopyTo(entryStream); }也可以用更簡短的寫法。
//?reference?System.IO.Compression using?(var?zip?=?ZipFile.Open("file.zip",?ZipArchiveMode.Create))zip.CreateEntryFromFile("file.txt",?"file.txt");AlexanderBrevig
既然壓縮整個文件夾是可以的,那可以通過創建一個臨時文件夾解決,然后借助臨時文件夾進行壓縮。
壓縮流程
創建一個臨時文件夾
將文件移動到文件夾
壓縮文件夾
刪除文件夾
解壓縮流程
解壓縮zip提取文件夾
從文件夾中提取出文件
刪除臨時文件夾
點評區
我個人在 zip 壓縮的業務時用的是 DotNetZip,非常方便,功能也非常強大,強烈推薦。
總結
以上是生活随笔為你收集整理的如何使用 C# 压缩单个文件?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WPF 实现加速小火箭~
- 下一篇: C# ActionT和 FuncT委托