压缩解压

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Framework
{
    
public class CompressionHelper
    {
        
public CompressionHelper()
        {
           
        }

        
public static byte[] CompressByte(byte[] bytes)
        {
            MemoryStream ms 
= new MemoryStream();
            GZipStream s 
= new GZipStream(ms, CompressionMode.Compress);
            s.Write(bytes, 
0, bytes.Length); 
            s.Close();
            
return ms.ToArray();
        }

        
public static byte[] DeCompressByte(byte[] bytes)
        {
            
byte[] writeData = new byte[4096];
            MemoryStream ms 
= new MemoryStream(bytes);
            Stream sm 
= new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress);
            MemoryStream outStream 
= new MemoryStream();
            
while (true)
            {
                
int size = sm.Read(writeData, 0, writeData.Length );
                
if (size >0)
                {
                    outStream.Write(writeData, 
0, size);
                }
                
else
                {
                    
break;
                }
            }
            sm.Close();
            
byte[] outArr = outStream.ToArray();
            outStream.Close();
            
return outArr;    
        }

        
public static string CompressString(string data)
        {
            
byte[] bytData = System.Text.Encoding.UTF8.GetBytes(data);
            MemoryStream ms 
= new MemoryStream();
            Stream s 
= new GZipStream(ms, CompressionMode.Compress);
            s.Write(bytData, 
0, bytData.Length);
            s.Close();
            
byte[] compressedData = (byte[])ms.ToArray();
            
return System.Convert.ToBase64String(compressedData, 0, compressedData.Length);
        }

        
public static string DeCompressString(string data)
        {
            System.Text.StringBuilder uncompressedString 
= new System.Text.StringBuilder();
            
byte[] writeData = new byte[4096];

            
byte[] bytData = System.Convert.FromBase64String(data);
            
int totalLength = 0;
            
int size = 0;

            Stream s 
= new GZipStream(new MemoryStream(bytData), CompressionMode.Decompress);
            
while (true)
            {
                size 
= s.Read(writeData, 0, writeData.Length);
                
if (size > 0)
                {
                    totalLength 
+= size;
                    uncompressedString.Append(System.Text.Encoding.UTF8.GetString(writeData, 
0, size));
                }
                
else
                {
                    
break;
                }
            }
            s.Close();
            
return uncompressedString.ToString();
        }
    }
}
posted @ 2008-07-01 22:07  angushine  阅读(202)  评论(0编辑  收藏  举报