ziparchive 的使用
範例一、將文字檔壓進 zip
using System.IO.Compression;
try
{
using (FileStream f = new FileStream(@"d:\release.zip", FileMode.Create))
{
}
using (FileStream zipToOpen = new FileStream(@"d:\release.zip", FileMode.Open))//新增一目標測試檔案(或記憶體位置)
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))//創一個 zip 執行個體
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");//創一個待壓縮的空檔(stream)進 zip
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))//用 StreamWriter 開啟該 stream,並將資料寫進去
{
writer.WriteLine("Readme.txt");
}
//再新增第二個 txt 檔進zip
ZipArchiveEntry readmeEntry2 = archive.CreateEntry("Readme2.txt");
using (StreamWriter writer = new StreamWriter(readmeEntry2.Open()))
{
writer.WriteLine("Readme2.txt");
}
}
}
Console.WriteLine("ok");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
範例二、將圖檔壓進 zip
using QRCoder;
using System.IO.Compression;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("The text which should be encoded.", QRCodeGenerator.ECCLevel.Q);
PngByteQRCode qrCode = new PngByteQRCode(qrCodeData);
byte[] qrCodeAsPngByteArr = qrCode.GetGraphic(4);
try
{
using (FileStream f = new FileStream(@"d:\release.zip", FileMode.Create))
{
}
using (FileStream zipToOpen = new FileStream(@"d:\release.zip", FileMode.Open))//新增一目標測試檔案(或記憶體位置)
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))//創一個 zip 執行個體
{
ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.png");//創一個待壓縮的空檔(stream)進 zip
using (BinaryWriter bw = new BinaryWriter(readmeEntry.Open()))
{
bw.Write(qrCodeAsPngByteArr);
}
}
}
Console.WriteLine("ok");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
參考資料: