Reputation: 2783
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
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
Reputation: 156524
object[][]
into a byte[]
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 object
s in memory, and those object
s can likewise have references to other object
s. 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