Compress/Decompress string/stringStream


#1

Is it possible to compress and then decompress string or stringStream using dotne or on the fly c# assembly?

What I found in the net:

using System.IO.Compression;
using System.Text;
using System.IO;

publicstaticstring Compress(string text)
{
 byte[] buffer = Encoding.UTF8.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 =newbyte[ms.Length];
 ms.Read(compressed, 0, compressed.Length);

 byte[] gzBuffer =newbyte[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);
}

publicstaticstring Decompress(string compressedText)
{
 byte[] gzBuffer = Convert.FromBase64String(compressedText);
 using (MemoryStream ms =new MemoryStream())
 {
  int msgLength = BitConverter.ToInt32(gzBuffer, 0);
  ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

  byte[] buffer =newbyte[msgLength];

  ms.Position = 0;
  using (GZipStream zip =new GZipStream(ms, CompressionMode.Decompress))
  {
   zip.Read(buffer, 0, buffer.Length);
  }

  return Encoding.UTF8.GetString(buffer);
 }
}

#2

If you have no plans to save the compressed data as .gz you can try DeflateStream instead.

(
fn compress bytes asdotnetobject:true =
(		
	local outputStream  = dotNetObject "system.io.memorystream" asdotnetobject:true
	local deflateStream = dotNetObject "system.io.compression.deflateStream" outputStream (dotNetClass "system.io.compression.CompressionLevel").Optimal asdotnetobject:true

	deflateStream.Write bytes 0 bytes.Length
	deflateStream.Flush()
	deflateStream.Close()
	
	outputStream.ToArray asdotnetobject:asdotnetobject
	
)

fn decompress bytes asdotnetobject:true =
(		
	local  inputStream  = dotNetObject "system.io.memorystream" bytes asdotnetobject:true
	local outputStream  = dotNetObject "system.io.memorystream" asdotnetobject:true
	
	local deflateStream = dotNetObject "system.io.compression.deflateStream" inputStream (dotNetClass "system.io.compression.CompressionMode").Decompress
	deflateStream.CopyTo outputStream
	deflateStream.Close()
	
	outputStream.ToArray asdotnetobject:asdotnetobject
	
)

fn StringAsBytes str = (dotNetClass "system.text.encoding").Utf8.GetBytes str asdotnetobject:true
fn StringFromBytes bytes = (dotNetClass "System.Text.Encoding").Utf8.GetString bytes


execute (StringFromBytes (decompress (compress (StringAsBytes "messageBox \"working...\""))))
)

#3

Thank you.