我建(基於一個CodeProject上的文章)包裝類(C#)來的MemoryStream使用GZipStream
來壓縮MemoryStream
。它壓縮好,但不解壓縮。我看過很多其他有相同問題的例子,我覺得我遵循所說的內容,但是當我解壓縮時仍然沒有獲得任何東西。這裏的壓縮和解壓方法:編程壓縮/解壓縮與GZipStream
public static byte[] Compress(byte[] bSource)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
{
gzip.Write(bSource, 0, bSource.Length);
gzip.Close();
}
return ms.ToArray();
}
}
public static byte[] Decompress(byte[] bSource)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true))
{
gzip.Read(bSource, 0, bSource.Length);
gzip.Close();
}
return ms.ToArray();
}
}
catch (Exception ex)
{
throw new Exception("Error decompressing byte array", ex);
}
}
這裏是我如何使用它的一個例子:
string sCompressed = Convert.ToBase64String(CompressionHelper.Compress("Some Text"));
// Other Processes
byte[] bReturned = CompressionHelper.Decompress(Convert.FromBase64String(sCompressed));
// bReturned has no elements after this line is executed