I have been using the following code to Compress data in .Net 4.0:
public static byte[] CompressData(byte[] data_toCompress)
{
using (MemoryStream outFile = new MemoryStream())
{
using (MemoryStream inFile = new MemoryStream(data_toCompress))
using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
{
inFile.CopyTo(Compress);
}
return outFile.ToArray();
}
}
However, in .Net 2.0 Stream.CopyTo method is not available. So, I tried making a replacement:
public static byte[] CompressData(byte[] data_toCompress)
{
using (MemoryStream outFile = new MemoryStream())
{
using (MemoryStream inFile = new MemoryStream(data_toCompress))
using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
{
//inFile.CopyTo(Compress);
Compress.Write(inFile.GetBuffer(), (int)inFile.Position, (int)(inFile.Length - inFile.Position));
}
return outFile.ToArray();
}
}
The compression fails, though, when using the above attempt - I get an error saying:
MemoryStream's internal buffer cannot be accessed.
Could anyone offer any help on this issue? I'm really not sure what else to do here.
Thank you, Evan
The open-source NuGet package Stream.CopyTo implements
Stream.CopyTo
for all versions of the .NET Framework.Available on GitHub and via NuGet (
Install-Package Stream.CopyTo
)This is the code straight out of
.Net 4.0
Stream.CopyTo
method (bufferSize is 4096):try to replace the line:
with:
you can get rid of this line completely:
Edit: find an example here: Why does gzip/deflate compressing a small file result in many trailing zeroes?
You should manually read and write between these 2 streams:
You can try
Why are you constructing a memory stream with an array and then trying to pull the array back out of the memory stream?
You could just do
Compress.Write(data_toCompress, 0, data_toCompress.Length);
If you need to replace the functionality of
CopyTo
, you can create a buffer array of some length, read data from the source stream and write that data to the destination stream.