Here it is:
public class Zip { //public static Encoding Encoding = System.Text.Encoding.Unicode; public static byte[] Compress(string text, Encoding Encoding = null) { if (text == null) return null; Encoding = Encoding ?? System.Text.Encoding.Unicode; // If the encoding is not specified use the Unicode var textBytes = Encoding.GetBytes(text); // Get the bytes according to the encoding var textStream = new MemoryStream(); // Make a stream of to be feeded by zip stream var zip = new GZipStream(textStream, CompressionMode.Compress); // Create a zip stream to receive zipped content in textStream zip.Write(textBytes, 0, textBytes.Length); // Write textBytes into zip stream, then zip will populate textStream zip.Close(); return textStream.ToArray(); // Get the bytes from the text stream } public static string Decompress(byte[] value, Encoding Encoding = null) { if (value == null) return null; Encoding = Encoding ?? System.Text.Encoding.Unicode; // If the encoding is not specified use the Uncide var inputStream = new MemoryStream(value); // Create a stream based on input value var outputStream = new MemoryStream(); // Create a stream to recieve output var zip = new GZipStream(inputStream, CompressionMode.Decompress); // Create a stream to decompress inputStream into outputStream byte[] bytes = new byte[4096]; int n; while ((n = zip.Read(bytes, 0, bytes.Length)) != 0) // While zip results output bytes from input stream { outputStream.Write(bytes, 0, n); // Write the unzipped bytes into output stream } zip.Close(); return Encoding.GetString(outputStream.ToArray()); // Get the string from unzipped bytes } }
When coding this and trying to execute, I get a Cannot Access a closed stream message by the return textStream.ToArray() line.
ReplyDeleteThis because the zip.Close() has already been done, the textStream is also freed...
Thank you! This helped!
ReplyDelete