title: Gzip compression and decompression in C#
body: <p>I'm trying to compress an string in one module and decompressing it in another module. Here is the code I'm using.</p>
  
  <p>Compress</p>
  
  <pre><code>public static string CompressString(string text)
  {
      byte[] buffer = Encoding.ASCII.GetBytes(text);
      MemoryStream ms = new MemoryStream();
      using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
      {
           zip.Write(buffer, 0, buffer.Length);
      }
  
      ms.Position = 0;
      MemoryStream outStream = new MemoryStream();
  
      byte[] compressed = new byte[ms.Length];
      ms.Read(compressed, 0, compressed.Length);
  
      byte[] gzBuffer = new byte[compressed.Length + 4];
      System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
      System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
      return Convert.ToBase64String(gzBuffer);
  }
  </code></pre>
  
  <p>Decompress</p>
  
  <pre><code>public static byte[] DecompressString(byte[] data)
  {
     using (var compressedStream = new MemoryStream(data))
     using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
       using (var resultStream = new MemoryStream())
       {
          zipStream.CopyTo(resultStream);
          return resultStream.ToArray();
       }
  }
  </code></pre>
  
  <p>Using it as:</p>
  
  <pre><code> DecompressString(System.Text.Encoding.ASCII.GetBytes(ip));
  </code></pre>
  
  <p>But, for above statement, I'm getting following error.</p>
  
  <blockquote>
    <p>{"The magic number in GZip header is not correct. Make sure you are
    passing in a GZip stream."}   System.SystemException
    {System.IO.InvalidDataException}</p>
  </blockquote>