Pages

Thursday, July 11, 2013

How to compress and decompress files in C# .NET 4.0 (GZip)

.NET 4.0 has a built-in gzip compress and decompress method.
.NET 4.5 has zip support.

This code shows how to use the .NET 4.0 gzip functionality. This also includes .NET 4.0 Client Profile
.NET 4.0 is supported by Windows XP and .NET 4.5 is NOT.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static void Decompress(FileInfo file)
{
 using (FileStream inFile = file.OpenRead())
 {
  //original file extension, ex. filename.exe.gz
  string orgName =
   file.FullName.Remove(file.FullName.Length - file.Extension.Length);

  //decompress file
  using (FileStream outFile = File.Create(orgName))
  {
   using (GZipStream Decompress = new GZipStream(inFile,
     CompressionMode.Decompress))
   {
    //write decompressed file
    byte[] buffer = new byte[4096];
    int index;
    while ((index = Decompress.Read(buffer, 0, buffer.Length)) != 0)
     outFile.Write(buffer, 0, index);
   }
  }
 }
}

public static void Compress(FileInfo file)
{
 using (FileStream inFile = file.OpenRead())
 {
  //create target file
  using (FileStream outFile =File.Create(file.FullName + ".gz"))
  {
   using (GZipStream Compress = new GZipStream(outFile,
     CompressionMode.Compress))
   {
    //write compressed file
    byte[] buffer = new byte[4096];
    int index;
    while ((index = inFile.Read(buffer, 0, buffer.Length)) != 0)
     Compress.Write(buffer, 0, index);
   }
  }
 }
}

No comments:

Post a Comment