简体   繁体   中英

C# GZipStream leaveOpen flag

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

I am trying to understand what does leaveOpen flag does. When this should be set to true or false?

This is the definition: leaveOpen:

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

In the .NET world several type of Stream s wrap another Stream to add kind of a new layer of logic , like compression/decompression, encryption, etc. In these cases, the stream gets another stream most likely as a constructor argument, like in your example. By convention (I guess..), when a wrapper Stream is disposed of, the wrapped Stream will get disposed of as well, or get closed in other words.

The flag leaveOpen means that when the wrapper stream gets closed (disposed), the underlying (wrapped) stream should be left open for further use.

It does exactly what it says, when leaveOpen is false (the default) it will dispose the stream you pass as the first argument when the GZipStream instance is disposed.

Depending on how you initialize your streams, you don't want to multiple-dispose objects, like in my usual coding pattern:

using var memoryStream = new MemoryStream();
using var fileStream = File.OpenRead(Path.Combine(repositoryPath, file));
using var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);
fileStream.CopyTo(gZipStream);
                    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM