Reputation: 5899
Is it possible to set compression level when using .NET's GZipStream
to compress a stream? It seems that Ionic Zip has a constructor for this, but I would rather not use a library just to get this feature.
Upvotes: 8
Views: 4199
Reputation: 879
If you look at the source code here: https://referencesource.microsoft.com/#system/sys/System/IO/compression/GZipStream.cs,b228c3ce72d4d124
// Implies mode = Compress
public GZipStream(Stream stream, CompressionLevel compressionLevel)
: this(stream, compressionLevel, false) {
}
// Implies mode = Compress
public GZipStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) {
deflateStream = new DeflateStream(stream, compressionLevel, leaveOpen);
deflateStream.SetFileFormatWriter(new GZipFormatter());
}
When passing the compression level the mode is always "Compress"!
Upvotes: 2
Reputation: 7490
As of .NET 4.5, the CompressionLevel
enum has been added to a couple constructors for GZipStream
.
The options are:
CompressionLevel.Optimal = 0
CompressionLevel.Fastest = 1
CompressionLevel.NoCompression = 2
So, you can now create a GZipStream
by passing a CompressionLevel
which determines how much to compress the data.
using (GZipStream compressionStream = new GZipStream(stream, CompressionLevel.Optimal))
{
// ...
}
More information is available in the GZipStream
documentation or the CompressionLevel
documentation.
Upvotes: 4
Reputation: 9712
I wouldn't go so far as to say it's impossible, but based on my review of MSDN I would say it's definitely not supported out of the box.
I think their excuse for this is summed up by:
Data is read in on a byte-by-byte basis, so it is not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data.
This posting says that internally it defaults to level 3, and that it has options (again, internally) to support changing the level of compression, but that it isn't exposed.
Upvotes: 3