I need to zip and unzip string
Here is code:
public static byte[] ZipStr(String str)
{
using (MemoryStream output = new MemoryStream())
using (DeflateStream gzip = new DeflateStream(output, CompressionMode.Compress))
using (StreamWriter writer = new StreamWriter(gzip))
{
writer.Write(str);
return output.ToArray();
}
}
and
public static string UnZipStr(byte[] input)
{
using (MemoryStream inputStream = new MemoryStream(input))
using (DeflateStream gzip = new DeflateStream(inputStream, CompressionMode.Decompress))
using (StreamReader reader = new StreamReader(gzip))
{
reader.ReadToEnd();
return System.Text.Encoding.UTF8.GetString(inputStream.ToArray());
}
}
It seems that there is error in UnZipStr method. Can somebody help me?
There are two separate problems. First of all, in
ZipStryou need to flush or close theStreamWriterand close theDeflateStreambefore reading from theMemoryStream.Secondly, in
UnZipStr, you’re constructing your result string from the compressed bytes ininputStream. You should be returning the result ofreader.ReadToEnd()instead.It would also be a good idea to specify the string encoding in the
StreamWriterandStreamReaderconstructors.Try the following code instead: