System.IO.Compression下的2个类搞了好久,原因看注释

 

System.IO.Compression下的2个类搞了好久,原因看注视

         public   static   byte [] Compression( byte [] data, CompressionMode mode)
        
{
            DeflateStream zip 
= null;
            
try
            
{
                
if (mode == CompressionMode.Compress)
                
{
                    MemoryStream ms 
= new MemoryStream();
                    zip 
= new DeflateStream(ms, mode, true);
                    zip.Write(data, 
0, data.Length);
                    zip.Close();               
//在返回处理结果前一定要把流关闭,否则取得的数据不完整
                    return ms.ToArray(); //我比较习惯于在finally中关闭,这个问题弄了好久。用using的话要把return放在using范围外
                }

                
else
                
{
                    MemoryStream ms 
= new MemoryStream();
                    ms.Write(data, 
0, data.Length);
                    ms.Flush();
                    ms.Position 
= 0;
                    zip 
= new DeflateStream(ms, mode, true);
                    MemoryStream os 
= new MemoryStream();
                    
int SIZE = 1024;
                    
byte[] buf = new byte[SIZE];
                    
int l = 0;
                    
do
                    
{
                        l 
= zip.Read(buf, 0, SIZE);  //第一次读入时居然返回0字节
                        if (l == 0) l = zip.Read(buf, 0, SIZE);//只好加了这行代码
                        os.Write(buf, 
0, l);
                    }
while(l != 0);
                    zip.Close();              
//在返回处理结果前一定要把流关闭,否则取得的数据不完整
                    return os.ToArray(); //我比较习惯于在finally中关闭,这个问题弄了好久。用using的话要把return放在using范围外
                }

            }

            
catch
            
{
                
return null;
            }

            
finally
            
{
                
if (zip != null) zip.Close();
            }

        }
 

你可能感兴趣的:(compression,byte,null)