Cannon
Cannon

Reputation: 2783

How do I compress Object[][] in C#

I need to compress object[][] in C#. I can use Gzip comrepss- decompress a byte[] but how to do it in such cases ?

Upvotes: 2

Views: 1885

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68677

Use binary serialization to turn it into a byte array which you'd then zip. Provided all the objects in the array are serializable, you can do the following

object[][] objects = new[] {new[] {"a"}};
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
using (GZipStream gZipStream = new GZipStream(File.OpenWrite("C:\\zipped.zip"), 
    CompressionMode.Compress))
{
    formatter.Serialize(gZipStream, objects);
}

//unzipping
using (GZipStream gZipStream = new GZipStream(File.OpenRead("C:\\zipped.zip"), 
    CompressionMode.Decompress))
{
    objects = (object[][])formatter.Deserialize(gZipStream);
    Console.WriteLine(objects[0][0]); //a
}

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156524

  1. Convert your object[][] into a byte[]
  2. Compress the byte[]

Step 1 is the hard part, and will require that all your objects are serializable, so that they can be converted into byte[]s.

The reason this is tricky is that the contents of an object[] are actually just memory references to various objects in memory, and those objects can likewise have references to other objects. Some can even reference specific system resources like I/O ports that have been allocated to them. It wouldn't make sense to send an object like this to a different computer, because that computer has not given the same resources to the object, right? So unless the classes have specifically indicated that they can be serialized and deserialized to a byte stream, you can't do anything with them.

Upvotes: 2

Related Questions