Compress and Decompress String using C#.NET GZipStream

GZip is one of the compression method available in System.IO.Compression namespance. Following are the methods to Compress or Decompress the String using GZipStream Class in C#.NET.

Compress the String

public static string GZipStringCompress(this string s)
{
 var bytes = Encoding.Unicode.GetBytes(s);
 using (var msi = new MemoryStream(bytes))
 using (var mso = new MemoryStream())
 {
  using (var gs = new GZipStream(mso, CompressionMode.Compress))
  {
   msi.CopyTo(gs);
  }
  return Convert.ToBase64String(mso.ToArray());
 }
}

Decompress the String

public static string GZipStringDecompress(this string s)
{
 var bytes = Convert.FromBase64String(s);
 using (var msi = new MemoryStream(bytes))
 using (var mso = new MemoryStream())
 {
  using (var gs = new GZipStream(msi, CompressionMode.Decompress))
  {
   gs.CopyTo(mso);
  }
  return Encoding.Unicode.GetString(mso.ToArray());
 }
}
We can also GZip the files uing GZipStream class. GZip compressed files will have the extension '.gz'. 
Note: For now, GZipStream doesn't support multiple files to a same '.gz' file. 

Compress the File

public void GZipFileCompress(string filepath)
{
 FileInfo fileToGZip = new FileInfo(filepath);
 FileInfo gZipFile = new FileInfo(string.Concat(fileToGZip.FullName, ".gz"));
     
 using (FileStream fileToGZipStream = fileToGZip.OpenRead())
 {
  using (FileStream gZipFileStream = gZipFile.Create())
   {
   using (GZipStream gzipStream = new GZipStream(gZipFileStream, CompressionMode.Compress))
   {
     fileToGZipStream.CopyTo(gzipStream);
   }
  }
 }
}

Decompress the File

public void GZipFileDecompress(string filepath)
{
    FileInfo gZipFile = new FileInfo(filepath);
 FileInfo decompressedFile = new FileInfo(string.Concat(gZipFile.FullName, ".txt"));
 using (FileStream gZipFileStream = gZipFile.OpenRead())
 {
  using (FileStream decompressedFileStream = File.Create(decompressedFile))
  {
   using (GZipStream gzipStream = new GZipStream(gZipFileStream, CompressionMode.Decompress))
   {
    gzipStream.CopyTo(decompressedFileStream);
   }
  }
 }
}

Happy Coding! 😊

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment