Mega Code Archive

 
Categories / C# Book / 07 Stream
 

0581 Compression

DeflateStream and GZipStream are two stream we can use to do the compression. GZipStream writes an additional protocol at the start and end including a CRC to detect for errors. GZipStream conforms to a standard recognized by other software. using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; class Program { static void Main() { string[] words = "this is a test".Split(); Random rand = new Random(); using (Stream s = File.Create("compressed.bin")) using (Stream ds = new DeflateStream(s, CompressionMode.Compress)) using (TextWriter w = new StreamWriter(ds)) for (int i = 0; i < 10; i++) w.Write(words[rand.Next(words.Length)] + " "); Console.WriteLine(new FileInfo("compressed.bin").Length); using (Stream s = File.OpenRead ("compressed.bin")){ using (Stream ds = new DeflateStream(s, CompressionMode.Decompress)){ using (TextReader r = new StreamReader(ds)){ Console.Write(r.ReadToEnd()); } } } } } The output: 124 test test this this test is a is test this