Decompress byte array

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 1722
private static byte[] Decompress(byte[] fileBytes)
{
int buffer_size = 100;

using (MemoryStream ms = new MemoryStream(fileBytes))
{
using (GZipStream gz = new GZipStream(ms,
CompressionMode.Decompress,
true))
{
byte[] bufferFooter = null;
int readOffset = 0;
int totalBytes = 0;
byte[] finalBuffer = null;
int uncompLength = 0;
//int compressedFileLength = fileBytes.Length;

// Get last 4 bytes (footer) as they contain the
// original length of the compressed bytes

// byte array to hold footer value
bufferFooter = new byte[4];

// Set position of MemoryStream end of stream
// minus the 4 bytes needed
ms.Position = ms.Length - 4;

// Fill the bufferFooter with the last 4 bytes
ms.Read(bufferFooter, 0, 4);

// Set Stream back to 0
ms.Position = 0;

// Convert footer bytes to the length.
uncompLength = BitConverter.ToInt32(bufferFooter, 0);

// Set a temporary buffer to hold the uncompressed
// information. We also make it slightly larger to
// ensure everything will fit. We will later trim
// off the unused bytes.
finalBuffer = new byte[uncompLength + buffer_size];

while (true)
{
// Read from stream up to buffer size. Note that return
// value is actual bytes read in case the number filled
// is less than we requested.
int bytesRead = gz.Read(finalBuffer,
readOffset,
buffer_size);

// If no bytes returned we are done
if (bytesRead == 0)
{
break;
}

readOffset += bytesRead;
totalBytes += bytesRead;
}

// Trim off unused bytes based
Array.Resize<byte>(ref finalBuffer, totalBytes);

return finalBuffer;
}
}
}

Comments or Responses

Login to post response