Läs på engelska Redigera

Dela via


GZipStream Constructors

Definition

Initializes a new instance of the GZipStream class.

Overloads

GZipStream(Stream, CompressionLevel)

Initializes a new instance of the GZipStream class by using the specified stream and compression level.

GZipStream(Stream, CompressionMode)

Initializes a new instance of the GZipStream class by using the specified stream and compression mode.

GZipStream(Stream, CompressionLevel, Boolean)

Initializes a new instance of the GZipStream class by using the specified stream and compression level, and optionally leaves the stream open.

GZipStream(Stream, CompressionMode, Boolean)

Initializes a new instance of the GZipStream class by using the specified stream and compression mode, and optionally leaves the stream open.

GZipStream(Stream, ZLibCompressionOptions, Boolean)

Initializes a new instance of the GZipStream class by using the specified stream, compression options, and optionally leaves the stream open.

GZipStream(Stream, CompressionLevel)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Initializes a new instance of the GZipStream class by using the specified stream and compression level.

C#
public GZipStream(System.IO.Stream stream, System.IO.Compression.CompressionLevel compressionLevel);

Parameters

stream
Stream

The stream to which compressed data is written.

compressionLevel
CompressionLevel

One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing data to the stream.

Exceptions

stream is null.

The stream does not support write operations such as compression. (The CanWrite property on the stream object is false.)

Remarks

You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the GZipStream class.

This constructor overload uses the compression mode Compress. To set the compression mode to another value, use the GZipStream(Stream, CompressionMode) or GZipStream(Stream, CompressionMode, Boolean) overload.

Applies to

.NET 10 och andra versioner
Produkt Versioner
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GZipStream(Stream, CompressionMode)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Initializes a new instance of the GZipStream class by using the specified stream and compression mode.

C#
public GZipStream(System.IO.Stream stream, System.IO.Compression.CompressionMode mode);

Parameters

stream
Stream

The stream to which compressed data is written or from which data to decompress is read.

mode
CompressionMode

One of the enumeration values that indicates whether to compress data to the stream or decompress data from the stream.

Exceptions

stream is null.

mode is not a valid CompressionMode enumeration value.

-or-

CompressionMode is Compress and CanWrite is false.

-or-

CompressionMode is Decompress and CanRead is false.

Examples

The following example shows how to set the compression mode when creating a GZipStream object.

C#
using System;
using System.IO;
using System.IO.Compression;

public class FileCompressionModeExample
{
    private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    private const string OriginalFileName = "original.txt";
    private const string CompressedFileName = "compressed.gz";
    private const string DecompressedFileName = "decompressed.txt";

    public static void Run()
    {
        CreateFileToCompress();
        CompressFile();
        DecompressFile();
        PrintResults();
        DeleteFiles();

        /*
         Output:

            The original file 'original.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

            The compressed file 'compressed.gz' is 283 bytes.

            The decompressed file 'decompressed.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
         */
    }

    private static void CreateFileToCompress() => File.WriteAllText(OriginalFileName, Message);

    private static void CompressFile()
    {
        using FileStream originalFileStream = File.Open(OriginalFileName, FileMode.Open);
        using FileStream compressedFileStream = File.Create(CompressedFileName);
        using var compressor = new GZipStream(compressedFileStream, CompressionMode.Compress);
        originalFileStream.CopyTo(compressor);
    }

    private static void DecompressFile()
    {
        using FileStream compressedFileStream = File.Open(CompressedFileName, FileMode.Open);
        using FileStream outputFileStream = File.Create(DecompressedFileName);
        using var decompressor = new GZipStream(compressedFileStream, CompressionMode.Decompress);
        decompressor.CopyTo(outputFileStream);
    }

    private static void PrintResults()
    {
        long originalSize = new FileInfo(OriginalFileName).Length;
        long compressedSize = new FileInfo(CompressedFileName).Length;
        long decompressedSize = new FileInfo(DecompressedFileName).Length;

        Console.WriteLine($"The original file '{OriginalFileName}' is {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\"");
        Console.WriteLine($"The compressed file '{CompressedFileName}' is {compressedSize} bytes.");
        Console.WriteLine($"The decompressed file '{DecompressedFileName}' is {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\"");
    }

    private static void DeleteFiles()
    {
        File.Delete(OriginalFileName);
        File.Delete(CompressedFileName);
        File.Delete(DecompressedFileName);
    }
}

Remarks

By default, GZipStream owns the underlying stream, so closing the stream parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created.

If an instance of the GZipStream class is created with the mode parameter equal to Compress and no further action occurs, the stream will appear as a valid, empty compressed file.

By default, the compression level is set to Optimal when the compression mode is Compress.

Applies to

.NET 10 och andra versioner
Produkt Versioner
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GZipStream(Stream, CompressionLevel, Boolean)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Initializes a new instance of the GZipStream class by using the specified stream and compression level, and optionally leaves the stream open.

C#
public GZipStream(System.IO.Stream stream, System.IO.Compression.CompressionLevel compressionLevel, bool leaveOpen);

Parameters

stream
Stream

The stream to which compressed data is written.

compressionLevel
CompressionLevel

One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing data to the stream.

leaveOpen
Boolean

true to leave the stream object open after disposing the GZipStream object; otherwise, false.

Exceptions

stream is null.

The stream does not support write operations such as compression. (The CanWrite property on the stream object is false.)

Examples

The following example shows how to set the compression level when creating a GZipStream object and how to leave the stream open.

C#
using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public static class MemoryWriteReadExample
{
    private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    private static readonly byte[] s_messageBytes = Encoding.ASCII.GetBytes(Message);

    public static void Run()
    {
        Console.WriteLine($"The original string length is {s_messageBytes.Length} bytes.");
        using var stream = new MemoryStream();
        CompressBytesToStream(stream);
        Console.WriteLine($"The compressed stream length is {stream.Length} bytes.");
        int decompressedLength = DecompressStreamToBytes(stream);
        Console.WriteLine($"The decompressed string length is {decompressedLength} bytes, same as the original length.");
        /*
         Output:
            The original string length is 445 bytes.
            The compressed stream length is 282 bytes.
            The decompressed string length is 445 bytes, same as the original length.
        */
    }

    private static void CompressBytesToStream(Stream stream)
    {
        using var compressor = new GZipStream(stream, CompressionLevel.SmallestSize, leaveOpen: true);
        compressor.Write(s_messageBytes, 0, s_messageBytes.Length);
    }

    private static int DecompressStreamToBytes(Stream stream)
    {
        stream.Position = 0;
        int bufferSize = 512;
        byte[] buffer = new byte[bufferSize];
        using var gzipStream = new GZipStream(stream, CompressionMode.Decompress);

        int totalRead = 0;
        while (totalRead < buffer.Length)
        {
            int bytesRead = gzipStream.Read(buffer.AsSpan(totalRead));
            if (bytesRead == 0) break;
            totalRead += bytesRead;
        }

        return totalRead;
    }
}

Remarks

You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the GZipStream class, and whether to leave the stream object open after disposing the GZipStream object.

This constructor overload uses the compression mode Compress. To set the compression mode to another value, use the GZipStream(Stream, CompressionMode) or GZipStream(Stream, CompressionMode, Boolean) overload.

Applies to

.NET 10 och andra versioner
Produkt Versioner
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GZipStream(Stream, CompressionMode, Boolean)

Source:
GZipStream.cs
Source:
GZipStream.cs
Source:
GZipStream.cs

Initializes a new instance of the GZipStream class by using the specified stream and compression mode, and optionally leaves the stream open.

C#
public GZipStream(System.IO.Stream stream, System.IO.Compression.CompressionMode mode, bool leaveOpen);

Parameters

stream
Stream

The stream to which compressed data is written or from which data to decompress is read.

mode
CompressionMode

One of the enumeration values that indicates whether to compress data to the stream or decompress data from the stream.

leaveOpen
Boolean

true to leave the stream open after disposing the GZipStream object; otherwise, false.

Exceptions

stream is null.

mode is not a valid CompressionMode value.

-or-

CompressionMode is Compress and CanWrite is false.

-or-

CompressionMode is Decompress and CanRead is false.

Remarks

By default, GZipStream owns the underlying stream, so closing the stream parameter also closes the underlying stream. The state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created.

If an instance of the GZipStream class is created with the mode parameter equal to Compress and no further action occurs, the stream will appear as a valid, empty compressed file.

By default, the compression level is set to Optimal when the compression mode is Compress.

Applies to

.NET 10 och andra versioner
Produkt Versioner
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

GZipStream(Stream, ZLibCompressionOptions, Boolean)

Initializes a new instance of the GZipStream class by using the specified stream, compression options, and optionally leaves the stream open.

C#
public GZipStream(System.IO.Stream stream, System.IO.Compression.ZLibCompressionOptions compressionOptions, bool leaveOpen = false);

Parameters

stream
Stream

The stream to which compressed data is written.

compressionOptions
ZLibCompressionOptions

The options for fine tuning the compression stream.

leaveOpen
Boolean

true to leave the stream object open after disposing the GZipStream object; otherwise, false.

Exceptions

stream or compressionOptions is null.

Applies to

.NET 10 och .NET 9
Produkt Versioner
.NET 9, 10