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 ZipStr you need to flush or close the StreamWriter and close the DeflateStream before reading from the MemoryStream.
Secondly, in UnZipStr, you're constructing your result string from the compressed bytes in inputStream. You should be returning the result of reader.ReadToEnd() instead.
It would also be a good idea to specify the string encoding in the StreamWriter and StreamReader constructors.
Try the following code instead:
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, System.Text.Encoding.UTF8))
{
writer.Write(str);
}
}
return output.ToArray();
}
}
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, System.Text.Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
}
}
Related
I'm trying to download a zip file and modify it before returning it. I expect the stream to be modified after adding additional files with ZipArchive in Update mode. However, it stays the same. What am I doing wrong?
using (WebClient webClient = new WebClient())
{
string url = "http://www.dynaexamples.com/examples-manual/ls-dyna_example.zip/at_download/file";
byte[] downloadedData = webClient.DownloadData(url);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(downloadedData, 0, downloadedData.Length);
Console.WriteLine(stream.Length.ToString()); //911616
ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update);
ZipArchiveEntry testFile = archive.CreateEntry("test.txt");
using (StreamWriter writer = new StreamWriter(testFile.Open()))
{
writer.WriteLine("test");
writer.Flush();
}
Console.WriteLine(stream.Length.ToString()); //911616
}
}
I'm trying to encode an image into a byte array and send it to a server.
the encoding and sending parts wok fine but my problem is that the byte array is too large and takes too long to send so I thought compressing it would make it go faster. but the actual problem is that I CAN NOT use system.io or streams. and I'm targeting .net 2.0.
Thank you.
using System.IO;
using System.IO.Compression;
code:
public static byte[] Compress(byte[] data)
{
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
{
dstream.Write(data, 0, data.Length);
}
return output.ToArray();
}
public static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream(data);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}
Updated
Use 7zip library:
http://www.splinter.com.au/compressing-using-the-7zip-lzma-algorithm-in/
// Convert the text into bytes
byte[] DataBytes = ASCIIEncoding.ASCII.GetBytes(OriginalText);
// Compress it
byte[] Compressed = SevenZip.Compression.LZMA.SevenZipHelper.Compress(DataBytes);
// Decompress it
byte[] Decompressed = SevenZip.Compression.LZMA.SevenZipHelper.Decompress(Compressed);
Compress
public static byte[] Compress(byte[] inputData)
{
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
{
dstream.Write(inputData, 0, inputData.Length);
}
return output.ToArray();
}
OR
public static byte[] Compress(byte[] inputData)
{
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
using (var compressIntoMs = new MemoryStream())
{
using (var gzs = new BufferedStream(new GZipStream(compressIntoMs,
CompressionMode.Compress), BUFFER_SIZE))
{
gzs.Write(inputData, 0, inputData.Length);
}
return compressIntoMs.ToArray();
}
}
Decompress
public static byte[] Decompress(byte[] inputData)
{
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
MemoryStream input = new MemoryStream(inputData);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
}
OR
public static byte[] Decompress(byte[] inputData)
{
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
using (var compressedMs = new MemoryStream(inputData))
{
using (var decompressedMs = new MemoryStream())
{
using (var gzs = new BufferedStream(new GZipStream(compressedMs, CompressionMode.Decompress), BUFFER_SIZE))
{
gzs.CopyTo(decompressedMs);
}
return decompressedMs.ToArray();
}
}
}
When i deserialize without GZip, it's done. But in deserializing with GZip i have deserialization error.
Serializing:
using (MemoryStream ms = new MemoryStream())
{
using (var compressionStream = new GZipStream(ms, CompressionMode.Compress))
{
serializator.Serialize(compressionStream, obj);
}
byte[] result = ms.ToArray();
return result;
}
Deserializing:
using (MemoryStream ms = new MemoryStream(_objBytes))
{
using (GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
return serializator.Deserialize(decompressionStream, null, objType, _objBytes.Length);
}
}
As stated in comments the number of bytes is wrong. Why are you ever specifying it? You can use overload without length parameter:
RuntimeTypeModel.Default.Deserialize(decompressionStream, null, objType);
Using several examples here on StackOverflow I thought the following code would decompress a gzip file then read the memory-stream and write it's content to the console. No errors occur but I get no output.
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(decompressedFileStream.Length);
decompressedFileStream.Read(memStream.GetBuffer(), 0, (int)decompressedFileStream.Length);
memStream.Position = 0;
var sr = new StreamReader(memStream);
var myStr = sr.ReadToEnd();
Console.WriteLine("Stream Output: " + myStr);
}
}
}
}
You are trying to copy an empty stream. "decompressedFileStream" is created by File.Create(), so it's empty. Swap "decompressedFileStream" to "decompressionStream" and you will be able to see your file content into "myStr".
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
MemoryStream memStream = new MemoryStream();
//memStream.SetLength(decompressedFileStream.Length); not necessary
decompressionStream.CopyTo(memStream);
memStream.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(memStream);
var myStr = sr.ReadToEnd();
Console.WriteLine("Stream Output: " + myStr);
}
}
}
}
Try this snippets. I use CopyTo instead of Read to copy the data to the memory stream and I use Seek() method instead of Position to return at the start of the memory stream.
I am trying to compress and decompress a Stream using Compression.DeflateStream. Compressing seems to work correctly since the code below compresses my Stream to a 110 bytes long array. However, reading the decompressed Stream results in an empty string.
class Program
{
static void Main(string[] args)
{
// Compress a random string value
string value = Path.GetRandomFileName();
byte[] compressedBytes;
using (var writer = new StreamWriter(new MemoryStream()))
{
writer.Write(value);
writer.Flush();
writer.BaseStream.Position = 0;
compressedBytes = Compress(writer.BaseStream);
}
// Decompress compressed bytes
Stream decompressedStream = Decompress(compressedBytes);
// here already applies: decompressedStream.Length == 0
using (var reader = new StreamReader(decompressedStream))
{
string decompressedValue = reader.ReadToEnd();
if (value == decompressedValue)
Console.WriteLine("Success");
else
Console.WriteLine("Failed");
}
}
private static byte[] Compress(Stream input)
{
using (var compressStream = new MemoryStream())
using (var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
{
input.CopyTo(compressor);
return compressStream.ToArray();
}
}
private static Stream Decompress(byte[] input)
{
var output = new MemoryStream();
using (var compressStream = new MemoryStream(input))
using (var decompressor = new DeflateStream(compressStream, CompressionMode.Decompress))
decompressor.CopyTo(output);
output.Position = 0;
return output;
}
}
Can anyone help me on this one?
Many thanks.
Fix your Compress function:
private static byte[] Compress(Stream input)
{
using(var compressStream = new MemoryStream())
using(var compressor = new DeflateStream(compressStream, CompressionMode.Compress))
{
input.CopyTo(compressor);
compressor.Close();
return compressStream.ToArray();
}
}
compressed stream was not flushed before returning the resulting byte array.
All those answers are far away from ideal form because all of you forgot that "using" disposing and closing streams its means that additional Close() is not needed. I think that ideal code will be like this:
public static class CompressionHelper
{
public static byte[] Compress(byte[] data)
{
byte[] compressArray = null;
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
{
deflateStream.Write(data, 0, data.Length);
}
compressArray = memoryStream.ToArray();
}
}
catch (Exception exception)
{
// do something !
}
return compressArray;
}
public static byte[] Decompress(byte[] data)
{
byte[] decompressedArray = null;
try
{
using (MemoryStream decompressedStream = new MemoryStream())
{
using (MemoryStream compressStream = new MemoryStream(data))
{
using (DeflateStream deflateStream = new DeflateStream(compressStream, CompressionMode.Decompress))
{
deflateStream.CopyTo(decompressedStream);
}
}
decompressedArray = decompressedStream.ToArray();
}
}
catch (Exception exception)
{
// do something !
}
return decompressedArray;
}
}
Try closing the streams:
class Program
{
static void Main(string[] args)
{
// Compress a random string value
string value = DateTime.Now.ToLongTimeString();
byte[] compressedBytes;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(value)))
{
compressedBytes = Compress(stream);
}
// Decompress compressed bytes
using (var decompressedStream = Decompress(compressedBytes))
using (var reader = new StreamReader(decompressedStream))
{
string decompressedValue = reader.ReadToEnd();
if (value == decompressedValue)
Console.WriteLine("Success");
else
Console.WriteLine("Failed");
}
}
public static byte[] Compress(Stream input)
{
using (var compressedStream = new MemoryStream())
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
input.CopyTo(zipStream);
zipStream.Close();
return compressedStream.ToArray();
}
}
public static Stream Decompress(byte[] data)
{
var output = new MemoryStream();
using(var compressedStream = new MemoryStream(data))
using(var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
{
zipStream.CopyTo(output);
zipStream.Close();
output.Position = 0;
return output;
}
}
}