Home > database >  typecast GzipStream to MemoryStream
typecast GzipStream to MemoryStream

Time:07-05

I need to write Gzip decompressed output to file (in binary).
Here is the powershell code i'm currently using:

$out = [IO.MemoryStream]::new()
$gzip = [IO.Compression.GzipStream]::new($in,
[IO.Compression.CompressionMode]::Decompress)
$gzip.CopyTo($out)
[IO.File]::WriteAllBytes('out.bin', $out.ToArray())

I want to make this code shorter, one-liner. So is there any way i can typecast IO.Compression.GzipStream to IO.MemoryStream ?

CodePudding user response:

You can't typecase GzipStream to MemoryStream but you can decompress to a file directly, without decompressing the whole input to memory first.

$out = [IO.File]::Create("$PWD\out.bin")
$gzip = [IO.Compression.GzipStream]::new( $in, [IO.Compression.CompressionMode]::Decompress )
$gzip.CopyTo( $out )
$out.Dispose()  # Close output file
  • Related