照著課本,練習Key:
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Numerics;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//DeflateStream
using(FileStream instream=new FileStream("doc1.txt",FileMode.Open))
using(FileStream outstream=new FileStream("out.def",FileMode.Create))
using (DeflateStream defstream=new DeflateStream(outstream,CompressionLevel.Optimal))
{
instream.CopyTo(defstream);
}
FileInfo info1 = new FileInfo("doc1.txt");
FileInfo info2 = new FileInfo("out.def");
Console.WriteLine($"Before Compress:{info1.Length}");
Console.WriteLine($"After Comoress:{info2.Length}");
//zip
string zipFile = "demo.zip";
using (FileStream outfs =File.Create(zipFile))
{
using (ZipArchive zip = new ZipArchive(outfs, ZipArchiveMode.Create))
{
ZipArchiveEntry etl = zip.CreateEntry("doc1.txt");
using (Stream stream = etl.Open())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write("範例文件 A");
}
}
ZipArchiveEntry et2 = zip.CreateEntry("doc2.txt");
using (Stream stream=et2.Open())
{
using(StreamWriter writer =new StreamWriter(stream))
{
writer.Write("範例文件 B");
}
}
}
}
using (FileStream instream = File.OpenRead(zipFile))
{
using(ZipArchive zip=new ZipArchive(instream))
{
foreach(ZipArchiveEntry et in zip.Entries)
{
using(Stream stream=et.Open())
{
using(FileStream fsout=File.Create(et.Name))
{
stream.CopyTo(fsout);
}
}
}
}
}
//GZipStream
string outFileName = "demo.gz";
using (FileStream fsIn = File.OpenRead("doc1.txt"))
using (FileStream fsOut = File.Create(outFileName))
using (GZipStream gz = new GZipStream(fsOut, CompressionMode.Compress))
{
fsIn.CopyTo(gz);
}
FileInfo info3 = new FileInfo("doc1.txt");
FileInfo info4 = new FileInfo(outFileName);
Console.WriteLine($"Before Compress:{info3.Length}");
Console.WriteLine($"After Comoress:{info4.Length}");
}
}
}
沒有留言:
張貼留言