How to compress a .net object instance using gzip

前端 未结 4 1755
执笔经年
执笔经年 2021-02-10 11:49

I am wanting to compress results from QUERYS of the database before adding them to the cache.

I want to be able to compress any reference type.

I have a working

4条回答
  •  独厮守ぢ
    2021-02-10 12:39

    Here is how this can be done.

    GzipStream: Provides methods and properties used to compress and decompress streams.

    Serialize object to Memory stream using binaryformatter and hook that memorystream to Gzipstream.

    Code to compress is as follows:

                public static byte[] ObjectToCompressedByteArray(object obj)
                        {
                            try
                            {
                                using (var memoryStream = new System.IO.MemoryStream())
                                {
                                    using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
                                    {
                                        var binaryFormatter = new BinaryFormatter();
                                        binaryFormatter.Serialize(gZipStream, obj);
                                    }
                                    return memoryStream.ToArray();
                                }
                            }
                            catch (Exception ex)
                            {
                                LoggerWrapper.CMLogger.LogMessage(
                                    $"EXCEPTION: BSExportImportHelper.ObjectToByteArray - : {ex.Message}", LoggerWrapper.CMLogger.CMLogLevel.Error);
                                throw;
                            }
    
                        }
    

提交回复
热议问题