压缩和解压缩数据流

  //压缩压缩后的字节数组
        public byte[] Compress(byte[] data)
        {
            MemoryStream ms 
= new MemoryStream();
            Stream zipStream 
= new GZipStream(ms, CompressionMode.Compress, true);
            zipStream.Write(data, 
0, data.Length);
            zipStream.Close();
            ms.Position 
= 0;
            
byte[] buffer = new byte[ms.Length];
            ms.Read(buffer, 
0,int.Parse(ms.Length.ToString()));
            
return buffer;
        }

//解压缩
  public static byte[] Decompress(byte[] data)
        {
            
try
            {
                MemoryStream ms 
= new MemoryStream(data);
                Stream zipStream 
= null;
                zipStream 
= new GZipStream(ms, CompressionMode.Decompress);
                
byte[] dc_data = null;
                dc_data 
= EtractBytesFormStream(zipStream, data.Length);
                
return dc_data;
            }
            
catch
            {
                
return null;
            }
        }


        
public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
        {
            
try
            {
                
byte[] data = null;
                
int totalBytesRead = 0;
                
while (true)
                {
                    Array.Resize(
ref data, totalBytesRead + dataBlock + 1);
                    
int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
                    
if (bytesRead == 0)
                    {
                        
break;
                    }
                    totalBytesRead 
+= bytesRead;
                }
                Array.Resize(
ref data, totalBytesRead);
                
return data;
            }
            
catch
            {
                
return null;
            }
        }
posted @ 2009-08-07 11:42  awp110  阅读(294)  评论(0编辑  收藏  举报