SoFunction
Updated on 2025-03-07

C# custom string compression and decompression methods

This article describes the methods of C# custom string compression and decompression. Share it for your reference. The details are as follows:

class ZipLib
{
 public static string Zip(string value)
 {
  //Transform string into byte[] 
  byte[] byteArray = new byte[];
  int indexBA = 0;
  foreach (char item in ())
  {
 byteArray[indexBA++] = (byte)item;
  }
  //Prepare for compress
   ms = new ();
   sw = new (ms,
 );
  //Compress
  (byteArray, 0, );
  //Close, DO NOT FLUSH cause bytes will go missing...
  ();
  //Transform byte[] zip data to string
  byteArray = ();
   sB = new ();
  foreach (byte item in byteArray)
  {
 ((char)item);
  }
  ();
  ();
  ();
  return ();
 }
 public static string UnZip(string value)
 {
  //Transform string into byte[]
  byte[] byteArray = new byte[];
  int indexBA = 0;
  foreach (char item in ())
  {
 byteArray[indexBA++] = (byte)item;
  }
  //Prepare for decompress
   ms = new (byteArray);
   sr = new (ms, );
  //Reset variable to collect uncompressed result
  byteArray = new byte[];
  //Decompress
  int rByte = (byteArray, 0, );
  //Transform byte[] unzip data to string
   sB = new (rByte);
  //Read the number of bytes GZipStream red and do not a for each bytes in
  //resultByteArray;
  for (int i = 0; i < rByte; i++)
  {
 ((char)byteArray[i]);
  }
  ();
  ();
  ();
  ();
  return ();
 }
}

How to use the code:

string str_org="aaaaaaaaaabbbbbbbbbbbbcccccccccdddddddd";
string str_comp = (str_org);
("str_comp:" + str_comp);
string str_uncomp = (str_comp);
("str_uncomp:" + str_uncomp);
();

I hope this article will be helpful to everyone's C# programming.