Following is the extension methods to use the standard .Net binary serializer, also to deserialize and compress and decompress it reduce the size of byte array:
public static class ObjectSerialize
{
public static byte[] Serialize(this Object obj)
{
if (obj == null)
{
return null;
}
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, obj);
var compressed = Compress(memoryStream.ToArray());
return compressed;
}
}
public static Object DeSerialize(this byte[] arrBytes)
{
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
var decompressed = Decompress(arrBytes);
memoryStream.Write(decompressed, 0, decompressed.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memoryStream);
}
}
public static byte[] Compress(byte[] input)
{
byte[] compressesData;
using (var outputStream = new MemoryStream())
{
using (var zip = new GZipStream(outputStream, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
}
compressesData = outputStream.ToArray();
}
return compressesData;
}
public static byte[] Decompress(byte[] input)
{
byte[] decompressedData;
using (var outputStream = new MemoryStream())
{
using (var inputStream = new MemoryStream(input))
{
using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
{
zip.CopyTo(outputStream);
}
}
decompressedData = outputStream.ToArray();
}
return decompressedData;
}
}
However I would suggest that you use the ProtoBuf
for binary serialization, more details here
It would work as simple as:
using ProtoBuf
var memoryStream = new MemoryStream();
// Serialize the Data to Stream
byte[] data = Serializer.Serialize(memoryStream, UserSessionLookupTable);
Here also you can include compression and decompression suggested above, in my experience ProBuf is much faster than standard Serialize.
For modifying anything in the dictionary you need to deserialize
by calling the method above in case of standard serializer:
var userSessionLookUpDeserialize =
(Dictionary<int,UserSessionInfo>)data.DeSerialize();
Following is the code for the ProtoBuf:
var userSessionLookUpDeserialize = Serializer.Deserialize<Dictionary<int, UserSessionInfo>>(new MemoryStream(deCompresseBytes));
Now make changes to the userSessionLookUpDeserialize