压缩:
public static void MemoryStreamCompress(string fileName, MemoryStream memStream) { FileStream fsWrite = File.OpenWrite(fileName); byte[] bytes = new byte[1 * 1024 * 1024]; GZipStream compressedzipStream = new GZipStream(fsWrite, CompressionMode.Compress); memStream.Position = 0; while(true) { int len = memStream.Read(bytes, 0, bytes.Length); if (len > 0) compressedzipStream.Write(bytes, 0, len); else break; } compressedzipStream.Close(); }
解压
public static MemoryStream MemoryStreamDeCompress(string fileName) { FileStream fsRead = File.OpenRead(fileName); byte[] bytes = new byte[1 * 1024 * 1024]; MemoryStream memStream = new MemoryStream(); GZipStream DecompressedzipStream = new GZipStream(fsRead, CompressionMode.Decompress); while (true) { int len = DecompressedzipStream.Read(bytes, 0, bytes.Length); if (len > 0) memStream.Write(bytes, 0, len); else break; } DecompressedzipStream.Close(); memStream.Position = 0; return memStream; }
如果是对象的话,可以直接对象序列化到GZipStream 的,相关代码涉及到公司就不放了,原理就是序列化时把 :MemoryStream做参数 传入GZipStream,然后GZipStream传入序列化函数,如果要获取流的大小,流close掉不能用流对象.Length,需要流对象.ToArray().Length才可以。
标签:MemoryStream,C#,bytes,GZipStream,len,new,memStream From: https://www.cnblogs.com/wuguoqiang/p/17460593.html