In one of our project,
we required to compress a file using zlib.net and store it in database in byte array format,
and on retrieving it, uncompressed byte array and create a file on disc.
Hope this post helps others …. !
download Zlib.net click here
Add reference of above dll.
using zlib;
public void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[2000];
int len;
while ((len = input.Read(buffer, 0, 2000)) > 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}
//compress function gets the file path to be compresss and fills in byte array arrCompressed
public void compress( ref byte[] arrCompressed, string strFileSrcPath)
{
MemoryStream oOutStream = new MemoryStream();
ZOutputStream ostream = new ZOutputStream(oOutStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);
FileStream inStream = new FileStream(strFileSrcPath, FileMode.Open);
try
{
CopyStream(inStream, ostream);
ostream.finish();
arrCompressed = oOutStream.ToArray();
}
finally
{
ostream.Close();
oOutStream.Close();
inStream.Close();
}
}
//uncompress function gets back file from compressed btye Array
public void uncompress( byte[] arrCompressed, string strFileDesName)
{
MemoryStream oInStream = new MemoryStream(arrCompressed);
ZInputStream oZInstream = new ZInputStream(oInStream);
MemoryStream oOutStream = new MemoryStream();
byte[] buffer = new byte[2000];
int len;
while ((len = oZInstream.read(buffer, 0, 2000)) > 0)
{
oOutStream.Write(buffer, 0, len);
}
oOutStream.Flush();
byte[] arrUncompressed = oOutStream.ToArray();
oZInstream.Close();
oOutStream.Close();
writeByteArrayToFile(arrUncompressed, strFileDesName);
}
//Writes Byte Array to Disc
public void writeByteArrayToFile(byte[] buff, string fileName)
{
try
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}