I want to unzip a compressed string so that the string of characters would become usable.
I successfully extract in an array of bytes the content of a downloaded file with the function WebClient.DownloadData(String).
The characters are logically compressed with the deflate method, because 7-Zip is giving this information when I download the file (in varying extensions) :
Thus, I am supposed to use the DeflateStream class to be able to decode the string, with the function Read(byte[] array, int offset, int count) ; reading a MemoryStream.
I use a simple function which I can find online :
public string UnzipString2(byte[] byteArrayCompressedContent)
{
try
{
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(byteArrayCompressedContent, 0);
memoryStream.Write(byteArrayCompressedContent, 4, byteArrayCompressedContent.Length - 4);
memoryStream.Position = 0;
var buffer = new byte[dataLength];
using (var deflateStream = new DeflateStream(memoryStream, System.IO.Compression.CompressionMode.Decompress))
{
deflateStream.Read(buffer, 0, buffer.Length);
deflateStream.Close();
}
return Encoding.UTF8.GetString(buffer);
}
}
catch (Exception e)
{
return "";
}
}
When we call the Read() function, it is giving an InvalidDataException : Found in valid data while decoding ; with the stacktrace
at System.IO.Compression.Inflater.DecodeDynamicBlockHeader()\r\n at System.IO.Compression.Inflater.Decode()\r\n at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)\r\n at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)\r\n
However, I still think that the information are compressed with the "deflate method". Is there a different/better/working way to read the data and decompress it in a String?