I have found a class that compresses and uncompresses data but need
some help with how to use part of it below is the deflate method which
compresses the string that I pass in, this works OK. At the end of
this message is the inflate method this is where I get stuck I know
that I need a byte array but because I am decompressing a string I
have no idea of how big the byte array will need to be in the end (the
inflate and deflate methods will be in two seperate exe's so I cann't
just path the length of the original string). Us there a way to keep
increasing the size of the byte array as I read more of it.
As an extra question what is the difference between the two methods of
reading the stream below (where buf is a byte array). Why do people
tend to prefer the second method?? Is it purly to do with being able
to read as much as possible if something goes wrong??
1)inStream.Read(buf,pos,buf.Length);
2)
while (true)
{
int numRead = inStream.Read(buf, pos, 4096);
if (numRead <= 0)
{
break;
}
pos += numRead;
}
Thnaks for any help,
Nick.
public string Deflate(string strToCompress)
{
string sReturn;
try
{
MemoryStream ms = new MemoryStream();
Deflater deflater = new Deflater(3);
DeflaterOutputStream outStream = new DeflaterOutputStream(ms,
deflater);
byte[] buf = m_Encoder.GetBytes(str);
outStream.Write(buf, 0, buf.Length);
outStream.Flush();
sReturn = MemoryStreamToString(outStream);
outStream.Finish();
}
catch(Exception ex)
{
Console.WriteLine("ERROR:" + ex.Message);
}
return sReturn;
}
public string Inflate(string strToUncompress)
{
string sReturn;
try
{
InflaterInputStream inStream = new
InflaterInputStream(StringToMemoryStream(strToUnco mpress));
byte[] buf2 = new byte[/*How big?*/];
// not sure how big to make this array
inStream.Read(buf2,pos,buf2.Length);
// or
while (true)
{
int numRead = inStream.Read(buf2, pos, 4096);
if (numRead <= 0)
{
break;
}
pos += numRead;
}
}
catch(Exception ex)
{
Console.WriteLine("ERROR:" + ex.Message);
}
return sReturn;
}
private MemoryStream StringToMemoryStream(String str)
{
return new MemoryStream(StringToByteArray(str));
}
private String MemoryStreamToString(MemoryStream memStream)
{
return ByteArrayToString(memStream.GetBuffer());
}
private Byte[] StringToByteArray(string str)
{
return m_Encoder.GetBytes(str);
}
private string ByteArrayToString(byte[] byteArray)
{
int NumberOfBytes = byteArray.Length;
return m_Encoder.GetString(byteArray, 0 , NumberOfBytes);
}