Zlib.Portable
Computes a CRC-32. The CRC-32 algorithm is parameterized - you
can set the polynomial and enable or disable bit
reversal. This can be used for GZIP, BZip2, or ZIP.
This type is used internally by DotNetZip; it is generally not used
directly by applications wishing to create, read, or manipulate zip
archive files.
Indicates the total number of bytes applied to the CRC.
Indicates the current CRC for all blocks slurped in.
Returns the CRC32 for the specified stream.
The stream over which to calculate the CRC32
the CRC32 calculation
Returns the CRC32 for the specified stream, and writes the input into the
output stream.
The stream over which to calculate the CRC32
The stream into which to deflate the input
the CRC32 calculation
Get the CRC32 for the given (word,byte) combo. This is a
computation defined by PKzip for PKZIP 2.0 (weak) encryption.
The word to start with.
The byte to combine it with.
The CRC-ized result.
Update the value for the running CRC32 using the given block of bytes.
This is useful when using the CRC32() class in a Stream.
block of bytes to slurp
starting point in the block
how many bytes within the block to slurp
Process one byte in the CRC.
the byte to include into the CRC .
Process a run of N identical bytes into the CRC.
This method serves as an optimization for updating the CRC when a
run of identical bytes is found. Rather than passing in a buffer of
length n, containing all identical bytes b, this method accepts the
byte value and the length of the (virtual) buffer - the length of
the run.
the byte to include into the CRC.
the number of times that byte should be repeated.
Combines the given CRC32 value with the current running total.
This is useful when using a divide-and-conquer approach to
calculating a CRC. Multiple threads can each calculate a
CRC32 on a segment of the data, and then combine the
individual CRC32 values at the end.
the crc value to be combined with this one
the length of data the CRC value was calculated on
Create an instance of the CRC32 class using the default settings: no
bit reversal, and a polynomial of 0xEDB88320.
Create an instance of the CRC32 class, specifying whether to reverse
data bits or not.
specify true if the instance should reverse data bits.
In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
want a CRC32 with compatibility with BZip2, you should pass true
here. In the CRC-32 used by GZIP and PKZIP, the bits are not
reversed; Therefore if you want a CRC32 with compatibility with
those, you should pass false.
Create an instance of the CRC32 class, specifying the polynomial and
whether to reverse data bits or not.
The polynomial to use for the CRC, expressed in the reversed (LSB)
format: the highest ordered bit in the polynomial value is the
coefficient of the 0th power; the second-highest order bit is the
coefficient of the 1 power, and so on. Expressed this way, the
polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320.
specify true if the instance should reverse data bits.
In the CRC-32 used by BZip2, the bits are reversed. Therefore if you
want a CRC32 with compatibility with BZip2, you should pass true
here for the reverseBits parameter. In the CRC-32 used by
GZIP and PKZIP, the bits are not reversed; Therefore if you want a
CRC32 with compatibility with those, you should pass false for the
reverseBits parameter.
Reset the CRC-32 class - clear the CRC "remainder register."
Use this when employing a single instance of this class to compute
multiple, distinct CRCs on multiple, distinct data blocks.
A Stream that calculates a CRC32 (a checksum) on all bytes read,
or on all bytes written.
This class can be used to verify the CRC of a ZipEntry when
reading from a stream, or to calculate a CRC when writing to a
stream. The stream should be used to either read, or write, but
not both. If you intermix reads and writes, the results are not
defined.
This class is intended primarily for use internally by the
DotNetZip library.
The default constructor.
Instances returned from this constructor will leave the underlying
stream open upon Close(). The stream uses the default CRC32
algorithm, which implies a polynomial of 0xEDB88320.
The underlying stream
The constructor allows the caller to specify how to handle the
underlying stream at close.
The stream uses the default CRC32 algorithm, which implies a
polynomial of 0xEDB88320.
The underlying stream
true to leave the underlying stream
open upon close of the CrcCalculatorStream; false otherwise.
A constructor allowing the specification of the length of the stream
to read.
The stream uses the default CRC32 algorithm, which implies a
polynomial of 0xEDB88320.
Instances returned from this constructor will leave the underlying
stream open upon Close().
The underlying stream
The length of the stream to slurp
A constructor allowing the specification of the length of the stream
to read, as well as whether to keep the underlying stream open upon
Close().
The stream uses the default CRC32 algorithm, which implies a
polynomial of 0xEDB88320.
The underlying stream
The length of the stream to slurp
true to leave the underlying stream
open upon close of the CrcCalculatorStream; false otherwise.
A constructor allowing the specification of the length of the stream
to read, as well as whether to keep the underlying stream open upon
Close(), and the CRC32 instance to use.
The stream uses the specified CRC32 instance, which allows the
application to specify how the CRC gets calculated.
The underlying stream
The length of the stream to slurp
true to leave the underlying stream
open upon close of the CrcCalculatorStream; false otherwise.
the CRC32 instance to use to calculate the CRC32
Gets the total number of bytes run through the CRC32 calculator.
This is either the total number of bytes read, or the total number of
bytes written, depending on the direction of this stream.
Provides the current CRC for all blocks slurped in.
The running total of the CRC is kept as data is written or read
through the stream. read this property after all reads or writes to
get an accurate CRC for the entire stream.
Indicates whether the underlying stream will be left open when the
CrcCalculatorStream is Closed.
Set this at any point before calling .
Read from the stream
the buffer to read
the offset at which to start
the number of bytes to read
the number of bytes actually read
Write to the stream.
the buffer from which to write
the offset at which to start writing
the number of bytes to write
Indicates whether the stream supports reading.
Indicates whether the stream supports seeking.
Always returns false.
Indicates whether the stream supports writing.
Flush the stream.
Returns the length of the underlying stream.
The getter for this property returns the total bytes read.
If you use the setter, it will throw
.
Seeking is not supported on this stream. This method always throws
N/A
N/A
N/A
This method always throws
N/A
A class for compressing and decompressing streams using the Deflate algorithm.
The DeflateStream is a Decorator on a . It adds DEFLATE compression or decompression to any
stream.
Using this stream, applications can compress or decompress data via stream
Read and Write operations. Either compresssion or decompression
can occur through either reading or writing. The compression format used is
DEFLATE, which is documented in IETF RFC 1951, "DEFLATE
Compressed Data Format Specification version 1.3.".
This class is similar to , except that
ZlibStream adds the RFC
1950 - ZLIB framing bytes to a compressed stream when compressing, or
expects the RFC1950 framing bytes when decompressing. The DeflateStream
does not.
Create a DeflateStream using the specified CompressionMode.
When mode is CompressionMode.Compress, the DeflateStream will use
the default compression level. The "captive" stream will be closed when
the DeflateStream is closed.
This example uses a DeflateStream to compress data from a file, and writes
the compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream which will be read or written.
Indicates whether the DeflateStream will compress or decompress.
Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel.
When mode is CompressionMode.Decompress, the level parameter is
ignored. The "captive" stream will be closed when the DeflateStream is
closed.
This example uses a DeflateStream to compress data from a file, and writes
the compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (Stream compressor = new DeflateStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".deflated")
Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to be read or written while deflating or inflating.
Indicates whether the DeflateStream will compress or decompress.
A tuning knob to trade speed for effectiveness.
Create a DeflateStream using the specified
CompressionMode, and explicitly specify whether the
stream should be left open after Deflation or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compression. Specify true for
the parameter to leave the stream open.
The DeflateStream will use the default compression level.
See the other overloads of this constructor for example code.
The stream which will be read or written. This is called the
"captive" stream in other places in this documentation.
Indicates whether the DeflateStream will compress or decompress.
true if the application would like the stream to
remain open after inflation/deflation.
Create a DeflateStream using the specified CompressionMode
and the specified CompressionLevel, and explicitly specify whether
the stream should be left open after Deflation or Inflation.
When mode is CompressionMode.Decompress, the level parameter is ignored.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
that will be re-read after
compression. Specify true for the parameter
to leave the stream open.
This example shows how to use a DeflateStream to compress data from
a file, and store the compressed data into another file.
using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
while (n != 0)
{
if (n > 0)
compressor.Write(buffer, 0, n);
n= input.Read(buffer, 0, buffer.Length);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".deflated")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using
The stream which will be read or written.
Indicates whether the DeflateStream will compress or decompress.
true if the application would like the stream to remain open after inflation/deflation.
A tuning knob to trade speed for effectiveness.
This property sets the flush behavior on the stream.
See the ZLIB documentation for the meaning of the flush behavior.
The size of the working buffer for the compression codec.
The working buffer is used for all stream operations. The default size is
1024 bytes. The minimum size is 128 bytes. You may get better performance
with a larger buffer. Then again, you might not. You would have to test
it.
Set this before the first call to Read() or Write() on the
stream. If you try to set it afterwards, it will throw.
The ZLIB strategy to be used during compression.
By tweaking this parameter, you may be able to optimize the compression for
data with particular characteristics.
Returns the total number of bytes input so far.
Returns the total number of bytes output so far.
Dispose the stream.
This may or may not result in a Close() call on the captive
stream. See the constructors that have a leaveOpen parameter
for more information.
Application code won't call this code directly. This method may be
invoked in two distinct scenarios. If disposing == true, the method
has been called directly or indirectly by a user's code, for example
via the public Dispose() method. In this case, both managed and
unmanaged resources can be referenced and disposed. If disposing ==
false, the method has been called by the runtime from inside the
object finalizer and this method should not reference other objects;
in that case only unmanaged resources must be referenced or
disposed.
true if the Dispose method was invoked by user code.
Indicates whether the stream can be read.
The return value depends on whether the captive stream supports reading.
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream can be written.
The return value depends on whether the captive stream supports writing.
Flush the stream.
Reading this property always throws a .
The position of the stream pointer.
Setting this property always throws a . Reading will return the total bytes
written out, if used in writing, or the total bytes read in, if used in
reading. The count may refer to compressed bytes or uncompressed bytes,
depending on how you've used the stream.
Read data from the stream.
If you wish to use the DeflateStream to compress data while
reading, you can create a DeflateStream with
CompressionMode.Compress, providing an uncompressed data stream.
Then call Read() on that DeflateStream, and the data read will be
compressed as you read. If you wish to use the DeflateStream to
decompress data while reading, you can create a DeflateStream with
CompressionMode.Decompress, providing a readable compressed data
stream. Then call Read() on that DeflateStream, and the data read
will be decompressed as you read.
A DeflateStream can be used for Read() or Write(), but not both.
The buffer into which the read data should be placed.
the offset within that data array to put the first byte read.
the number of bytes to read.
the number of bytes actually read
Calling this method always throws a .
this is irrelevant, since it will always throw!
this is irrelevant, since it will always throw!
irrelevant!
Calling this method always throws a .
this is irrelevant, since it will always throw!
Write data to the stream.
If you wish to use the DeflateStream to compress data while
writing, you can create a DeflateStream with
CompressionMode.Compress, and a writable output stream. Then call
Write() on that DeflateStream, providing uncompressed data
as input. The data sent to the output stream will be the compressed form
of the data written. If you wish to use the DeflateStream to
decompress data while writing, you can create a DeflateStream with
CompressionMode.Decompress, and a writable output stream. Then
call Write() on that stream, providing previously compressed
data. The data sent to the output stream will be the decompressed form of
the data written.
A DeflateStream can be used for Read() or Write(),
but not both.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
Compress a string into a byte array using DEFLATE (RFC 1951).
Uncompress it with .
DeflateStream.UncompressString(byte[])
DeflateStream.CompressBuffer(byte[])
GZipStream.CompressString(string)
ZlibStream.CompressString(string)
A string to compress. The string will first be encoded
using UTF8, then compressed.
The string in compressed form
Compress a byte array into a new byte array using DEFLATE.
Uncompress it with .
DeflateStream.CompressString(string)
DeflateStream.UncompressBuffer(byte[])
GZipStream.CompressBuffer(byte[])
ZlibStream.CompressBuffer(byte[])
A buffer to compress.
The data in compressed form
Uncompress a DEFLATE'd byte array into a single string.
DeflateStream.CompressString(String)
DeflateStream.UncompressBuffer(byte[])
GZipStream.UncompressString(byte[])
ZlibStream.UncompressString(byte[])
A buffer containing DEFLATE-compressed data.
The uncompressed string
Uncompress a DEFLATE'd byte array into a byte array.
DeflateStream.CompressBuffer(byte[])
DeflateStream.UncompressString(byte[])
GZipStream.UncompressBuffer(byte[])
ZlibStream.UncompressBuffer(byte[])
A buffer containing data that has been compressed with DEFLATE.
The data in uncompressed form
A class for compressing and decompressing GZIP streams.
The GZipStream is a Decorator on a
. It adds GZIP compression or decompression to any
stream.
Like the System.IO.Compression.GZipStream in the .NET Base Class Library, the
Ionic.Zlib.GZipStream can compress while writing, or decompress while
reading, but not vice versa. The compression method used is GZIP, which is
documented in IETF RFC
1952, "GZIP file format specification version 4.3".
A GZipStream can be used to decompress data (through Read()) or
to compress data (through Write()), but not both.
If you wish to use the GZipStream to compress data, you must wrap it
around a write-able stream. As you call Write() on the GZipStream, the
data will be compressed into the GZIP format. If you want to decompress data,
you must wrap the GZipStream around a readable stream that contains an
IETF RFC 1952-compliant stream. The data will be decompressed as you call
Read() on the GZipStream.
Though the GZIP format allows data from multiple files to be concatenated
together, this stream handles only a single segment of GZIP format, typically
representing a single file.
This class is similar to and .
ZlibStream handles RFC1950-compliant streams.
handles RFC1951-compliant streams. This class handles RFC1952-compliant streams.
The comment on the GZIP stream.
The GZIP format allows for each file to optionally have an associated
comment stored with the file. The comment is encoded with the ISO-8859-1
code page. To include a comment in a GZIP stream you create, set this
property before calling Write() for the first time on the
GZipStream.
When using GZipStream to decompress, you can retrieve this property
after the first call to Read(). If no comment has been set in the
GZIP bytestream, the Comment property will return null
(Nothing in VB).
The FileName for the GZIP stream.
The GZIP format optionally allows each file to have an associated
filename. When compressing data (through Write()), set this
FileName before calling Write() the first time on the GZipStream.
The actual filename is encoded into the GZIP bytestream with the
ISO-8859-1 code page, according to RFC 1952. It is the application's
responsibility to insure that the FileName can be encoded and decoded
correctly with this code page.
When decompressing (through Read()), you can retrieve this value
any time after the first Read(). In the case where there was no filename
encoded into the GZIP bytestream, the property will return null (Nothing
in VB).
The last modified time for the GZIP stream.
GZIP allows the storage of a last modified time with each GZIP entry.
When compressing data, you can set this before the first call to
Write(). When decompressing, you can retrieve this value any time
after the first call to Read().
The CRC on the GZIP stream.
This is used for internal error checking. You probably don't need to look at this property.
Create a GZipStream using the specified CompressionMode.
When mode is CompressionMode.Compress, the GZipStream will use the
default compression level.
As noted in the class documentation, the CompressionMode (Compress
or Decompress) also establishes the "direction" of the stream. A
GZipStream with CompressionMode.Compress works only through
Write(). A GZipStream with
CompressionMode.Decompress works only through Read().
This example shows how to use a GZipStream to compress data.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
This example shows how to use a GZipStream to uncompress a file.
private void GunZipFile(string filename)
{
if (!filename.EndsWith(".gz))
throw new ArgumentException("filename");
var DecompressedFile = filename.Substring(0,filename.Length-3);
byte[] working = new byte[WORKING_BUFFER_SIZE];
int n= 1;
using (System.IO.Stream input = System.IO.File.OpenRead(filename))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(DecompressedFile))
{
while (n !=0)
{
n= decompressor.Read(working, 0, working.Length);
if (n > 0)
{
output.Write(working, 0, n);
}
}
}
}
}
}
Private Sub GunZipFile(ByVal filename as String)
If Not (filename.EndsWith(".gz)) Then
Throw New ArgumentException("filename")
End If
Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
Dim working(WORKING_BUFFER_SIZE) as Byte
Dim n As Integer = 1
Using input As Stream = File.OpenRead(filename)
Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
Using output As Stream = File.Create(UncompressedFile)
Do
n= decompressor.Read(working, 0, working.Length)
If n > 0 Then
output.Write(working, 0, n)
End IF
Loop While (n > 0)
End Using
End Using
End Using
End Sub
The stream which will be read or written.
Indicates whether the GZipStream will compress or decompress.
Create a GZipStream using the specified CompressionMode and
the specified CompressionLevel.
The CompressionMode (Compress or Decompress) also establishes the
"direction" of the stream. A GZipStream with
CompressionMode.Compress works only through Write(). A
GZipStream with CompressionMode.Decompress works only
through Read().
This example shows how to use a GZipStream to compress a file into a .gz file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
{
using (Stream compressor = new GZipStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".gz")
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to be read or written while deflating or inflating.
Indicates whether the GZipStream will compress or decompress.
A tuning knob to trade speed for effectiveness.
Create a GZipStream using the specified CompressionMode, and
explicitly specify whether the stream should be left open after Deflation
or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compressed data has been written
to it. Specify true for the parameter to leave
the stream open.
The (Compress or Decompress) also
establishes the "direction" of the stream. A GZipStream with
CompressionMode.Compress works only through Write(). A GZipStream
with CompressionMode.Decompress works only through Read().
The GZipStream will use the default compression level. If you want
to specify the compression level, see .
See the other overloads of this constructor for example code.
The stream which will be read or written. This is called the "captive"
stream in other places in this documentation.
Indicates whether the GZipStream will compress or decompress.
true if the application would like the base stream to remain open after
inflation/deflation.
Create a GZipStream using the specified CompressionMode and the
specified CompressionLevel, and explicitly specify whether the
stream should be left open after Deflation or Inflation.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
memory stream that will be re-read after compressed data has been written
to it. Specify true for the parameter to
leave the stream open.
As noted in the class documentation, the CompressionMode (Compress
or Decompress) also establishes the "direction" of the stream. A
GZipStream with CompressionMode.Compress works only through
Write(). A GZipStream with CompressionMode.Decompress works only
through Read().
This example shows how to use a GZipStream to compress data.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream which will be read or written.
Indicates whether the GZipStream will compress or decompress.
true if the application would like the stream to remain open after inflation/deflation.
A tuning knob to trade speed for effectiveness.
This property sets the flush behavior on the stream.
The size of the working buffer for the compression codec.
The working buffer is used for all stream operations. The default size is
1024 bytes. The minimum size is 128 bytes. You may get better performance
with a larger buffer. Then again, you might not. You would have to test
it.
Set this before the first call to Read() or Write() on the
stream. If you try to set it afterwards, it will throw.
Returns the total number of bytes input so far.
Returns the total number of bytes output so far.
Dispose the stream.
This may or may not result in a Close() call on the captive
stream. See the constructors that have a leaveOpen parameter
for more information.
This method may be invoked in two distinct scenarios. If disposing
== true, the method has been called directly or indirectly by a
user's code, for example via the public Dispose() method. In this
case, both managed and unmanaged resources can be referenced and
disposed. If disposing == false, the method has been called by the
runtime from inside the object finalizer and this method should not
reference other objects; in that case only unmanaged resources must
be referenced or disposed.
indicates whether the Dispose method was invoked by user code.
Indicates whether the stream can be read.
The return value depends on whether the captive stream supports reading.
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream can be written.
The return value depends on whether the captive stream supports writing.
Flush the stream.
Reading this property always throws a .
The position of the stream pointer.
Setting this property always throws a . Reading will return the total bytes
written out, if used in writing, or the total bytes read in, if used in
reading. The count may refer to compressed bytes or uncompressed bytes,
depending on how you've used the stream.
Read and decompress data from the source stream.
With a GZipStream, decompression is done through reading.
byte[] working = new byte[WORKING_BUFFER_SIZE];
using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
{
using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
{
using (var output = System.IO.File.Create(_DecompressedFile))
{
int n;
while ((n= decompressor.Read(working, 0, working.Length)) !=0)
{
output.Write(working, 0, n);
}
}
}
}
The buffer into which the decompressed data should be placed.
the offset within that data array to put the first byte read.
the number of bytes to read.
the number of bytes actually read
Calling this method always throws a .
irrelevant; it will always throw!
irrelevant; it will always throw!
irrelevant!
Calling this method always throws a .
irrelevant; this method will always throw!
Write data to the stream.
If you wish to use the GZipStream to compress data while writing,
you can create a GZipStream with CompressionMode.Compress, and a
writable output stream. Then call Write() on that GZipStream,
providing uncompressed data as input. The data sent to the output stream
will be the compressed form of the data written.
A GZipStream can be used for Read() or Write(), but not
both. Writing implies compression. Reading implies decompression.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
Compress a string into a byte array using GZip.
Uncompress it with .
A string to compress. The string will first be encoded
using UTF8, then compressed.
The string in compressed form
Compress a byte array into a new byte array using GZip.
Uncompress it with .
A buffer to compress.
The data in compressed form
Uncompress a GZip'ed byte array into a single string.
A buffer containing GZIP-compressed data.
The uncompressed string
Uncompress a GZip'ed byte array into a byte array.
A buffer containing data that has been compressed with GZip.
The data in uncompressed form
A class for compressing streams using the
Deflate algorithm with multiple threads.
This class performs DEFLATE compression through writing. For
more information on the Deflate algorithm, see IETF RFC 1951,
"DEFLATE Compressed Data Format Specification version 1.3."
This class is similar to , except
that this class is for compression only, and this implementation uses an
approach that employs multiple worker threads to perform the DEFLATE. On
a multi-cpu or multi-core computer, the performance of this class can be
significantly higher than the single-threaded DeflateStream, particularly
for larger streams. How large? Anything over 10mb is a good candidate
for parallel compression.
The tradeoff is that this class uses more memory and more CPU than the
vanilla DeflateStream, and also is less efficient as a compressor. For
large files the size of the compressed data stream can be less than 1%
larger than the size of a compressed data stream from the vanialla
DeflateStream. For smaller files the difference can be larger. The
difference will also be larger if you set the BufferSize to be lower than
the default value. Your mileage may vary. Finally, for small files, the
ParallelDeflateOutputStream can be much slower than the vanilla
DeflateStream, because of the overhead associated to using the thread
pool.
Create a ParallelDeflateOutputStream.
This stream compresses data written into it via the DEFLATE
algorithm (see RFC 1951), and writes out the compressed byte stream.
The instance will use the default compression level, the default
buffer sizes and the default number of threads and buffers per
thread.
This class is similar to ,
except that this implementation uses an approach that employs
multiple worker threads to perform the DEFLATE. On a multi-cpu or
multi-core computer, the performance of this class can be
significantly higher than the single-threaded DeflateStream,
particularly for larger streams. How large? Anything over 10mb is
a good candidate for parallel compression.
This example shows how to use a ParallelDeflateOutputStream to compress
data. It reads a file, compresses it, and writes the compressed data to
a second, output file.
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n= -1;
String outputFile = fileToCompress + ".compressed";
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(outputFile))
{
using (Stream compressor = new ParallelDeflateOutputStream(raw))
{
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Dim outputFile As String = (fileToCompress & ".compressed")
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(outputFile)
Using compressor As Stream = New ParallelDeflateOutputStream(raw)
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to which compressed data will be written.
Create a ParallelDeflateOutputStream using the specified CompressionLevel.
See the
constructor for example code.
The stream to which compressed data will be written.
A tuning knob to trade speed for effectiveness.
Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
when the ParallelDeflateOutputStream is closed.
See the
constructor for example code.
The stream to which compressed data will be written.
true if the application would like the stream to remain open after inflation/deflation.
Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
when the ParallelDeflateOutputStream is closed.
See the
constructor for example code.
The stream to which compressed data will be written.
A tuning knob to trade speed for effectiveness.
true if the application would like the stream to remain open after inflation/deflation.
Create a ParallelDeflateOutputStream using the specified
CompressionLevel and CompressionStrategy, and specifying whether to
leave the captive stream open when the ParallelDeflateOutputStream is
closed.
See the
constructor for example code.
The stream to which compressed data will be written.
A tuning knob to trade speed for effectiveness.
By tweaking this parameter, you may be able to optimize the compression for
data with particular characteristics.
true if the application would like the stream to remain open after inflation/deflation.
The ZLIB strategy to be used during compression.
The maximum number of buffer pairs to use.
This property sets an upper limit on the number of memory buffer
pairs to create. The implementation of this stream allocates
multiple buffers to facilitate parallel compression. As each buffer
fills up, this stream uses
ThreadPool.QueueUserWorkItem()
to compress those buffers in a background threadpool thread. After a
buffer is compressed, it is re-ordered and written to the output
stream.
A higher number of buffer pairs enables a higher degree of
parallelism, which tends to increase the speed of compression on
multi-cpu computers. On the other hand, a higher number of buffer
pairs also implies a larger memory consumption, more active worker
threads, and a higher cpu utilization for any compression. This
property enables the application to limit its memory consumption and
CPU utilization behavior depending on requirements.
For each compression "task" that occurs in parallel, there are 2
buffers allocated: one for input and one for output. This property
sets a limit for the number of pairs. The total amount of storage
space allocated for buffering will then be (N*S*2), where N is the
number of buffer pairs, S is the size of each buffer (). By default, DotNetZip allocates 4 buffer
pairs per CPU core, so if your machine has 4 cores, and you retain
the default buffer size of 128k, then the
ParallelDeflateOutputStream will use 4 * 4 * 2 * 128kb of buffer
memory in total, or 4mb, in blocks of 128kb. If you then set this
property to 8, then the number will be 8 * 2 * 128kb of buffer
memory, or 2mb.
CPU utilization will also go up with additional buffers, because a
larger number of buffer pairs allows a larger number of background
threads to compress in parallel. If you find that parallel
compression is consuming too much memory or CPU, you can adjust this
value downward.
The default value is 16. Different values may deliver better or
worse results, depending on your priorities and the dynamic
performance characteristics of your storage and compute resources.
This property is not the number of buffer pairs to use; it is an
upper limit. An illustration: Suppose you have an application that
uses the default value of this property (which is 16), and it runs
on a machine with 2 CPU cores. In that case, DotNetZip will allocate
4 buffer pairs per CPU core, for a total of 8 pairs. The upper
limit specified by this property has no effect.
The application can set this value at any time, but it is effective
only before the first call to Write(), which is when the buffers are
allocated.
The size of the buffers used by the compressor threads.
The default buffer size is 128k. The application can set this value
at any time, but it is effective only before the first Write().
Larger buffer sizes implies larger memory consumption but allows
more efficient compression. Using smaller buffer sizes consumes less
memory but may result in less effective compression. For example,
using the default buffer size of 128k, the compression delivered is
within 1% of the compression delivered by the single-threaded . On the other hand, using a
BufferSize of 8k can result in a compressed data stream that is 5%
larger than that delivered by the single-threaded
DeflateStream. Excessively small buffer sizes can also cause
the speed of the ParallelDeflateOutputStream to drop, because of
larger thread scheduling overhead dealing with many many small
buffers.
The total amount of storage space allocated for buffering will be
(N*S*2), where N is the number of buffer pairs, and S is the size of
each buffer (this property). There are 2 buffers used by the
compressor, one for input and one for output. By default, DotNetZip
allocates 4 buffer pairs per CPU core, so if your machine has 4
cores, then the number of buffer pairs used will be 16. If you
accept the default value of this property, 128k, then the
ParallelDeflateOutputStream will use 16 * 2 * 128kb of buffer memory
in total, or 4mb, in blocks of 128kb. If you set this property to
64kb, then the number will be 16 * 2 * 64kb of buffer memory, or
2mb.
The CRC32 for the data that was written out, prior to compression.
This value is meaningful only after a call to Close().
The total number of uncompressed bytes processed by the ParallelDeflateOutputStream.
This value is meaningful only after a call to Close().
Write data to the stream.
To use the ParallelDeflateOutputStream to compress data, create a
ParallelDeflateOutputStream with CompressionMode.Compress, passing a
writable output stream. Then call Write() on that
ParallelDeflateOutputStream, providing uncompressed data as input. The
data sent to the output stream will be the compressed form of the data
written.
To decompress data, use the class.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
Flush the stream.
Close the stream.
You must call Close on the stream to guarantee that all of the data written in has
been compressed, and the compressed data has been written out.
Dispose the object
Because ParallelDeflateOutputStream is IDisposable, the
application must call this method when finished using the instance.
This method is generally called implicitly upon exit from
a using scope in C# (Using in VB).
Resets the stream for use with another stream.
Because the ParallelDeflateOutputStream is expensive to create, it
has been designed so that it can be recycled and re-used. You have
to call Close() on the stream first, then you can call Reset() on
it, to use it again on another stream.
The new output stream for this era.
ParallelDeflateOutputStream deflater = null;
foreach (var inputFile in listOfFiles)
{
string outputFile = inputFile + ".compressed";
using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
{
using (var outStream = System.IO.File.Create(outputFile))
{
if (deflater == null)
deflater = new ParallelDeflateOutputStream(outStream,
CompressionLevel.Best,
CompressionStrategy.Default,
true);
deflater.Reset(outStream);
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
deflater.Write(buffer, 0, n);
}
}
}
}
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream supports Read operations.
Always returns false.
Indicates whether the stream supports Write operations.
Returns true if the provided stream is writable.
Reading this property always throws a NotSupportedException.
Returns the current position of the output stream.
Because the output gets written by a background thread,
the value may change asynchronously. Setting this
property always throws a NotSupportedException.
This method always throws a NotSupportedException.
The buffer into which data would be read, IF THIS METHOD
ACTUALLY DID ANYTHING.
The offset within that data array at which to insert the
data that is read, IF THIS METHOD ACTUALLY DID
ANYTHING.
The number of bytes to write, IF THIS METHOD ACTUALLY DID
ANYTHING.
nothing.
This method always throws a NotSupportedException.
The offset to seek to....
IF THIS METHOD ACTUALLY DID ANYTHING.
The reference specifying how to apply the offset.... IF
THIS METHOD ACTUALLY DID ANYTHING.
nothing. It always throws.
This method always throws a NotSupportedException.
The new value for the stream length.... IF
THIS METHOD ACTUALLY DID ANYTHING.
Map from a distance to a distance code.
No side effects. _dist_code[256] and _dist_code[257] are never used.
Describes how to flush the current deflate operation.
The different FlushType values are useful when using a Deflate in a streaming application.
No flush at all.
Closes the current block, but doesn't flush it to
the output. Used internally only in hypothetical
scenarios. This was supposed to be removed by Zlib, but it is
still in use in some edge cases.
Use this during compression to specify that all pending output should be
flushed to the output buffer and the output should be aligned on a byte
boundary. You might use this in a streaming communication scenario, so that
the decompressor can get all input data available so far. When using this
with a ZlibCodec, AvailableBytesIn will be zero after the call if
enough output space has been provided before the call. Flushing will
degrade compression and so it should be used only when necessary.
Use this during compression to specify that all output should be flushed, as
with FlushType.Sync, but also, the compression state should be reset
so that decompression can restart from this point if previous compressed
data has been damaged or if random access is desired. Using
FlushType.Full too often can significantly degrade the compression.
Signals the end of the compression/decompression stream.
The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
None means that the data will be simply stored, with no change at all.
If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
cannot be opened with the default zip reader. Use a different CompressionLevel.
Same as None.
The fastest but least effective compression.
A synonym for BestSpeed.
A little slower, but better, than level 1.
A little slower, but better, than level 2.
A little slower, but better, than level 3.
A little slower than level 4, but with better compression.
The default compression level, with a good balance of speed and compression efficiency.
A synonym for Default.
Pretty good compression!
Better compression than Level7!
The "best" compression, where best means greatest reduction in size of the input data stream.
This is also the slowest compression.
A synonym for BestCompression.
Describes options for how the compression algorithm is executed. Different strategies
work better on different sorts of data. The strategy parameter can affect the compression
ratio and the speed of compression but not the correctness of the compresssion.
The default strategy is probably the best for normal data.
The Filtered strategy is intended to be used most effectively with data produced by a
filter or predictor. By this definition, filtered data consists mostly of small
values with a somewhat random distribution. In this case, the compression algorithm
is tuned to compress them better. The effect of Filtered is to force more Huffman
coding and less string matching; it is a half-step between Default and HuffmanOnly.
Using HuffmanOnly will force the compressor to do Huffman encoding only, with no
string matching.
An enum to specify the direction of transcoding - whether to compress or decompress.
Used to specify that the stream should compress the data.
Used to specify that the stream should decompress the data.
A general purpose exception class for exceptions in the Zlib library.
The ZlibException class captures exception information generated
by the Zlib library.
This ctor collects a message attached to the exception.
the message for the exception.
Performs an unsigned bitwise right shift with the specified number
Number to operate on
Ammount of bits to shift
The resulting number from the shift operation
Reads a number of characters from the current source TextReader and writes
the data to the target array at the specified index.
The source TextReader to read from
Contains the array of characteres read from the source TextReader.
The starting index of the target array.
The maximum number of characters to read from the source TextReader.
The number of characters read. The number will be less than or equal to
count depending on the data available in the source TextReader. Returns -1
if the end of the stream is reached.
Computes an Adler-32 checksum.
The Adler checksum is similar to a CRC checksum, but faster to compute, though less
reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
is a required part of the "ZLIB" standard. Applications will almost never need to
use this class directly.
Calculates the Adler32 checksum.
This is used within ZLIB. You probably don't need to use this directly.
To compute an Adler32 checksum on a byte array:
var adler = Adler.Adler32(0, null, 0, 0);
adler = Adler.Adler32(adler, buffer, index, length);
Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
This class compresses and decompresses data according to the Deflate algorithm
and optionally, the ZLIB format, as documented in RFC 1950 - ZLIB and RFC 1951 - DEFLATE.
The buffer from which data is taken.
An index into the InputBuffer array, indicating where to start reading.
The number of bytes available in the InputBuffer, starting at NextIn.
Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
The class will update this number as calls to Inflate/Deflate are made.
Total number of bytes read so far, through all calls to Inflate()/Deflate().
Buffer to store output data.
An index into the OutputBuffer array, indicating where to start writing.
The number of bytes available in the OutputBuffer, starting at NextOut.
Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
The class will update this number as calls to Inflate/Deflate are made.
Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
used for diagnostics, when something goes wrong!
The compression level to use in this codec. Useful only in compression mode.
The number of Window Bits to use.
This gauges the size of the sliding window, and hence the
compression effectiveness as well as memory consumption. It's best to just leave this
setting alone if you don't know what it is. The maximum value is 15 bits, which implies
a 32k window.
The compression strategy to use.
This is only effective in compression. The theory offered by ZLIB is that different
strategies could potentially produce significant differences in compression behavior
for different data sets. Unfortunately I don't have any good recommendations for how
to set it differently. When I tested changing the strategy I got minimally different
compression performance. It's best to leave this property alone if you don't have a
good feel for it. Or, you may want to produce a test harness that runs through the
different strategy options and evaluates them on different file types. If you do that,
let me know your results.
The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
Create a ZlibCodec.
If you use this default constructor, you will later have to explicitly call
InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
or decompress.
Create a ZlibCodec that either compresses or decompresses.
Indicates whether the codec should compress (deflate) or decompress (inflate).
Initialize the inflation state.
It is not necessary to call this before using the ZlibCodec to inflate data;
It is implicitly called when you call the constructor.
Z_OK if everything goes well.
Initialize the inflation state with an explicit flag to
govern the handling of RFC1950 header bytes.
By default, the ZLIB header defined in RFC 1950 is expected. If
you want to read a zlib stream you should specify true for
expectRfc1950Header. If you have a deflate stream, you will want to specify
false. It is only necessary to invoke this initializer explicitly if you
want to specify false.
whether to expect an RFC1950 header byte
pair when reading the stream of data to be inflated.
Z_OK if everything goes well.
Initialize the ZlibCodec for inflation, with the specified number of window bits.
The number of window bits to use. If you need to ask what that is,
then you shouldn't be calling this initializer.
Z_OK if all goes well.
Initialize the inflation state with an explicit flag to govern the handling of
RFC1950 header bytes.
If you want to read a zlib stream you should specify true for
expectRfc1950Header. In this case, the library will expect to find a ZLIB
header, as defined in RFC
1950, in the compressed stream. If you will be reading a DEFLATE or
GZIP stream, which does not have such a header, you will want to specify
false.
whether to expect an RFC1950 header byte pair when reading
the stream of data to be inflated.
The number of window bits to use. If you need to ask what that is,
then you shouldn't be calling this initializer.
Z_OK if everything goes well.
Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
AvailableBytesOut before calling this method.
private void InflateBuffer()
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec decompressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
MemoryStream ms = new MemoryStream(DecompressedBytes);
int rc = decompressor.InitializeInflate();
decompressor.InputBuffer = CompressedBytes;
decompressor.NextIn = 0;
decompressor.AvailableBytesIn = CompressedBytes.Length;
decompressor.OutputBuffer = buffer;
// pass 1: inflate
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("inflating: " + decompressor.Message);
ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
decompressor.NextOut = 0;
decompressor.AvailableBytesOut = buffer.Length;
rc = decompressor.Inflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("inflating: " + decompressor.Message);
if (buffer.Length - decompressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
}
while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
decompressor.EndInflate();
}
The flush to use when inflating.
Z_OK if everything goes well.
Ends an inflation session.
Call this after successively calling Inflate(). This will cause all buffers to be flushed.
After calling this you cannot call Inflate() without a intervening call to one of the
InitializeInflate() overloads.
Z_OK if everything goes well.
I don't know what this does!
Z_OK if everything goes well.
Initialize the ZlibCodec for deflation operation.
The codec will use the MAX window bits and the default level of compression.
int bufferSize = 40000;
byte[] CompressedBytes = new byte[bufferSize];
byte[] DecompressedBytes = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
compressor.InitializeDeflate(CompressionLevel.Default);
compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
compressor.NextIn = 0;
compressor.AvailableBytesIn = compressor.InputBuffer.Length;
compressor.OutputBuffer = CompressedBytes;
compressor.NextOut = 0;
compressor.AvailableBytesOut = CompressedBytes.Length;
while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
{
compressor.Deflate(FlushType.None);
}
while (true)
{
int rc= compressor.Deflate(FlushType.Finish);
if (rc == ZlibConstants.Z_STREAM_END) break;
}
compressor.EndDeflate();
Z_OK if all goes well. You generally don't need to check the return code.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
The codec will use the maximum window bits (15) and the specified
CompressionLevel. It will emit a ZLIB stream as it compresses.
The compression level for the codec.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
and the explicit flag governing whether to emit an RFC1950 header byte pair.
The codec will use the maximum window bits (15) and the specified CompressionLevel.
If you want to generate a zlib stream, you should specify true for
wantRfc1950Header. In this case, the library will emit a ZLIB
header, as defined in RFC
1950, in the compressed stream.
The compression level for the codec.
whether to emit an initial RFC1950 byte pair in the compressed stream.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
and the specified number of window bits.
The codec will use the specified number of window bits and the specified CompressionLevel.
The compression level for the codec.
the number of window bits to use. If you don't know what this means, don't use this method.
Z_OK if all goes well.
Initialize the ZlibCodec for deflation operation, using the specified
CompressionLevel, the specified number of window bits, and the explicit flag
governing whether to emit an RFC1950 header byte pair.
The compression level for the codec.
whether to emit an initial RFC1950 byte pair in the compressed stream.
the number of window bits to use. If you don't know what this means, don't use this method.
Z_OK if all goes well.
Deflate one batch of data.
You must have set InputBuffer and OutputBuffer before calling this method.
private void DeflateBuffer(CompressionLevel level)
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
ZlibCodec compressor = new ZlibCodec();
Console.WriteLine("\n============================================");
Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
MemoryStream ms = new MemoryStream();
int rc = compressor.InitializeDeflate(level);
compressor.InputBuffer = UncompressedBytes;
compressor.NextIn = 0;
compressor.AvailableBytesIn = UncompressedBytes.Length;
compressor.OutputBuffer = buffer;
// pass 1: deflate
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.None);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new Exception("deflating: " + compressor.Message);
ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// pass 2: finish and flush
do
{
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
compressor.EndDeflate();
ms.Seek(0, SeekOrigin.Begin);
CompressedBytes = new byte[compressor.TotalBytesOut];
ms.Read(CompressedBytes, 0, CompressedBytes.Length);
}
whether to flush all data as you deflate. Generally you will want to
use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
flush everything.
Z_OK if all goes well.
End a deflation session.
Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
Z_OK if all goes well.
Reset a codec for another deflation session.
Call this to reset the deflation state. For example if a thread is deflating
non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
block and before the next Deflate(None) of the second block.
Z_OK if all goes well.
Set the CompressionStrategy and CompressionLevel for a deflation session.
the level of compression to use.
the strategy to use for compression.
Z_OK if all goes well.
Set the dictionary to be used for either Inflation or Deflation.
The dictionary bytes to use.
Z_OK if all goes well.
A bunch of constants used in the Zlib interface.
The maximum number of window bits for the Deflate algorithm.
The default number of window bits for the Deflate algorithm.
indicates everything is A-OK
Indicates that the last operation reached the end of the stream.
The operation ended in need of a dictionary.
There was an error with the stream - not enough data, not open and readable, etc.
There was an error with the data - not enough data, bad data, etc.
There was an error with the working buffer.
The size of the working buffer used in the ZlibCodec class. Defaults to 8192 bytes.
The minimum size of the working buffer used in the ZlibCodec class. Currently it is 128 bytes.
Represents a Zlib stream for compression or decompression.
The ZlibStream is a Decorator on a . It adds ZLIB compression or decompression to any
stream.
Using this stream, applications can compress or decompress data via
stream Read() and Write() operations. Either compresssion or
decompression can occur through either reading or writing. The compression
format used is ZLIB, which is documented in IETF RFC 1950, "ZLIB Compressed
Data Format Specification version 3.3". This implementation of ZLIB always uses
DEFLATE as the compression method. (see IETF RFC 1951, "DEFLATE
Compressed Data Format Specification version 1.3.")
The ZLIB format allows for varying compression methods, window sizes, and dictionaries.
This implementation always uses the DEFLATE compression method, a preset dictionary,
and 15 window bits by default.
This class is similar to , except that it adds the
RFC1950 header and trailer bytes to a compressed stream when compressing, or expects
the RFC1950 header and trailer bytes when decompressing. It is also similar to the
.
Create a ZlibStream using the specified CompressionMode.
When mode is CompressionMode.Compress, the ZlibStream
will use the default compression level. The "captive" stream will be
closed when the ZlibStream is closed.
This example uses a ZlibStream to compress a file, and writes the
compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".zlib")
Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream which will be read or written.
Indicates whether the ZlibStream will compress or decompress.
Create a ZlibStream using the specified CompressionMode and
the specified CompressionLevel.
When mode is CompressionMode.Decompress, the level parameter is ignored.
The "captive" stream will be closed when the ZlibStream is closed.
This example uses a ZlibStream to compress data from a file, and writes the
compressed data to another file.
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (Stream compressor = new ZlibStream(raw,
CompressionMode.Compress,
CompressionLevel.BestCompression))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
}
Using input As Stream = File.OpenRead(fileToCompress)
Using raw As FileStream = File.Create(fileToCompress & ".zlib")
Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
End Using
The stream to be read or written while deflating or inflating.
Indicates whether the ZlibStream will compress or decompress.
A tuning knob to trade speed for effectiveness.
Create a ZlibStream using the specified CompressionMode, and
explicitly specify whether the captive stream should be left open after
Deflation or Inflation.
When mode is CompressionMode.Compress, the ZlibStream will use
the default compression level.
This constructor allows the application to request that the captive stream
remain open after the deflation or inflation occurs. By default, after
Close() is called on the stream, the captive stream is also
closed. In some cases this is not desired, for example if the stream is a
that will be re-read after
compression. Specify true for the parameter to leave the stream
open.
See the other overloads of this constructor for example code.
The stream which will be read or written. This is called the
"captive" stream in other places in this documentation.
Indicates whether the ZlibStream will compress or decompress.
true if the application would like the stream to remain
open after inflation/deflation.
Create a ZlibStream using the specified CompressionMode
and the specified CompressionLevel, and explicitly specify
whether the stream should be left open after Deflation or Inflation.
This constructor allows the application to request that the captive
stream remain open after the deflation or inflation occurs. By
default, after Close() is called on the stream, the captive
stream is also closed. In some cases this is not desired, for example
if the stream is a that will be
re-read after compression. Specify true for the parameter to leave the stream open.
When mode is CompressionMode.Decompress, the level parameter is
ignored.
This example shows how to use a ZlibStream to compress the data from a file,
and store the result into another file. The filestream remains open to allow
additional data to be written to it.
using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
{
using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
{
using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
byte[] buffer = new byte[WORKING_BUFFER_SIZE];
int n;
while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
{
compressor.Write(buffer, 0, n);
}
}
}
// can write additional data to the output stream here
}
Using output As FileStream = File.Create(fileToCompress & ".zlib")
Using input As Stream = File.OpenRead(fileToCompress)
Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
Dim buffer As Byte() = New Byte(4096) {}
Dim n As Integer = -1
Do While (n <> 0)
If (n > 0) Then
compressor.Write(buffer, 0, n)
End If
n = input.Read(buffer, 0, buffer.Length)
Loop
End Using
End Using
' can write additional data to the output stream here.
End Using
The stream which will be read or written.
Indicates whether the ZlibStream will compress or decompress.
true if the application would like the stream to remain open after
inflation/deflation.
A tuning knob to trade speed for effectiveness. This parameter is
effective only when mode is CompressionMode.Compress.
This property sets the flush behavior on the stream.
Sorry, though, not sure exactly how to describe all the various settings.
The size of the working buffer for the compression codec.
The working buffer is used for all stream operations. The default size is
1024 bytes. The minimum size is 128 bytes. You may get better performance
with a larger buffer. Then again, you might not. You would have to test
it.
Set this before the first call to Read() or Write() on the
stream. If you try to set it afterwards, it will throw.
Returns the total number of bytes input so far.
Returns the total number of bytes output so far.
Dispose the stream.
This may or may not result in a Close() call on the captive
stream. See the constructors that have a leaveOpen parameter
for more information.
This method may be invoked in two distinct scenarios. If disposing
== true, the method has been called directly or indirectly by a
user's code, for example via the public Dispose() method. In this
case, both managed and unmanaged resources can be referenced and
disposed. If disposing == false, the method has been called by the
runtime from inside the object finalizer and this method should not
reference other objects; in that case only unmanaged resources must
be referenced or disposed.
indicates whether the Dispose method was invoked by user code.
Indicates whether the stream can be read.
The return value depends on whether the captive stream supports reading.
Indicates whether the stream supports Seek operations.
Always returns false.
Indicates whether the stream can be written.
The return value depends on whether the captive stream supports writing.
Flush the stream.
Reading this property always throws a .
The position of the stream pointer.
Setting this property always throws a . Reading will return the total bytes
written out, if used in writing, or the total bytes read in, if used in
reading. The count may refer to compressed bytes or uncompressed bytes,
depending on how you've used the stream.
Read data from the stream.
If you wish to use the ZlibStream to compress data while reading,
you can create a ZlibStream with CompressionMode.Compress,
providing an uncompressed data stream. Then call Read() on that
ZlibStream, and the data read will be compressed. If you wish to
use the ZlibStream to decompress data while reading, you can create
a ZlibStream with CompressionMode.Decompress, providing a
readable compressed data stream. Then call Read() on that
ZlibStream, and the data will be decompressed as it is read.
A ZlibStream can be used for Read() or Write(), but
not both.
The buffer into which the read data should be placed.
the offset within that data array to put the first byte read.
the number of bytes to read.
the number of bytes read
Calling this method always throws a .
The offset to seek to....
IF THIS METHOD ACTUALLY DID ANYTHING.
The reference specifying how to apply the offset.... IF
THIS METHOD ACTUALLY DID ANYTHING.
nothing. This method always throws.
Calling this method always throws a .
The new value for the stream length.... IF
THIS METHOD ACTUALLY DID ANYTHING.
Write data to the stream.
If you wish to use the ZlibStream to compress data while writing,
you can create a ZlibStream with CompressionMode.Compress,
and a writable output stream. Then call Write() on that
ZlibStream, providing uncompressed data as input. The data sent to
the output stream will be the compressed form of the data written. If you
wish to use the ZlibStream to decompress data while writing, you
can create a ZlibStream with CompressionMode.Decompress, and a
writable output stream. Then call Write() on that stream,
providing previously compressed data. The data sent to the output stream
will be the decompressed form of the data written.
A ZlibStream can be used for Read() or Write(), but not both.
The buffer holding data to write to the stream.
the offset within that data array to find the first byte to write.
the number of bytes to write.
Compress a string into a byte array using ZLIB.
Uncompress it with .
A string to compress. The string will first be encoded
using UTF8, then compressed.
The string in compressed form
Compress a byte array into a new byte array using ZLIB.
Uncompress it with .
A buffer to compress.
The data in compressed form
Uncompress a ZLIB-compressed byte array into a single string.
A buffer containing ZLIB-compressed data.
The uncompressed string
Uncompress a ZLIB-compressed byte array into a byte array.
A buffer containing ZLIB-compressed data.
The data in uncompressed form
Provides a text encoder for the iso-8859-1 encoding, aka Latin1 encoding,
for platforms that do not support it, for example on Silverlight or some
Compact Framework platforms.
Gets the name registered with the
Internet Assigned Numbers Authority (IANA) for the current encoding.
Always returns "iso-8859-1".
Encodes a set of characters from a character array into
a byte array.
The actual number of bytes written into .
The character array containing the set of characters to encode.
The index of the first character to encode.
The number of characters to encode.
The byte array to contain the resulting sequence of bytes.
The index at which to start writing the resulting sequence of bytes.
Decodes a sequence of bytes from the specified byte array into the specified character array.
The actual number of characters written into .
The byte array containing the sequence of bytes to decode.
The index of the first byte to decode.
The number of bytes to decode.
The character array to contain the resulting set of characters.
The index at which to start writing the resulting set of characters.
Calculates the number of bytes produced by encoding a set of characters
from the specified character array.
The number of bytes produced by encoding the specified characters. This class
alwas returns the value of .
Calculates the number of characters produced by decoding a sequence
of bytes from the specified byte array.
The number of characters produced by decoding the specified sequence of bytes. This class
alwas returns the value of .
Calculates the maximum number of bytes produced by encoding the specified number of characters.
The maximum number of bytes produced by encoding the specified number of characters. This
class alwas returns the value of .
The number of characters to encode.
Calculates the maximum number of characters produced by decoding the specified number of bytes.
The maximum number of characters produced by decoding the specified number of bytes. This class
alwas returns the value of .
The number of bytes to decode.
Gets the number of characters that are supported by this encoding.
This property returns a maximum value of 256, as the encoding class
only supports single byte encodings (1 byte == 256 possible values).
Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization.
1
Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization.
1
Provides a platform-specific volume separator character.
1
Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the class.
A character array of invalid path characters for the current platform.
1
A platform-specific separator character used to separate path strings in environment variables.
1