I have a big object in memory which I want to save as a blob into database.
I want to compress it before saving because database server is usually not local.
This is what I have at the moment:
using (var memoryStream = new MemoryStream())
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream msCompressed = new MemoryStream())
using (GZipStream gZipStream = new GZipStream(msCompressed, CompressionMode.Compress))
using (MemoryStream msDecompressed = new MemoryStream())
new BinaryFormatter().Serialize(msDecompressed, obj);
byte byteArray = msDecompressed.ToArray();
gZipStream.Write(byteArray, 0, byteArray.Length);
GZipStream from .NET 3.5 doesn't allow you to set compression level. This parameter was introduced in .NET 4.5, but I don't know if it will give you better result or upgrade is suitable for you. Built in algorythm is not very optimal, due to patents AFAIK. So in 3.5 is only one way to get better compression is to use third party library like SDK provided by 7zip or SharpZipLib. Probably yo ushould experiment a little bit with different libs to get better compression of your data.