日期:2014-05-19  浏览次数:21012 次

请问如何把DeflateStream中的资料读出并转为byte[]?
MemoryStream   ms   =   new   MemoryStream();
DeflateStream   dStream   =   new   DeflateStream(ms,   CompressionMode.Compress);
dStream.Write(toBeCompressedData,   0,   toBeCompressedData.Length);

toBeCompressedData是byte[],是需要压缩的资料,请问如何从dStream中读出压缩后的资料并转为byte[]?

注:dStream不能用read,会出错.

------解决方案--------------------
public byte[] Compress(Stream stream)
{
MemoryStream ms = new MemoryStream();
zipStream = new DeflateStream(ms, CompressionMode.Compress);
byte[] buffer = new byte[BUFFER_SIZE];
int count = stream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
zipStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffer.Length);
}
zipStream.Flush();
zipStream.Close();
byte[] compressed = ms.ToArray();
ms.Close();
return compressed;
}

public byte[] Decompress(Stream inputStream)
{
MemoryStream ms = new MemoryStream();
zipStream = new DeflateStream(inputStream, CompressionMode.Decompress);
byte[] buffer = new byte[BUFFER_SIZE];
int count = zipStream.Read(buffer, 0, buffer.Length);
while (count > 0)
{
ms.Write(buffer, 0, count);
count = zipStream.Read(buffer, 0, buffer.Length);
}
zipStream.Close();
byte[] decompressed = ms.ToArray();
ms.Close();
return decompressed;
}