Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active July 12, 2023 21:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save santisq/830cbdf46dc88cbc25fd53a1a0501504 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.IO.Compression;
using System.Management.Automation;
using System.Reflection;
namespace Testing;
public static class Test
{
private static bool? _isCore;
private const byte GzipPreamble1 = 0x1f;
private const byte GzipPreamble2 = 0x8b;
private const byte GzipPreamble3 = 0x08;
private static bool IsCoreCLR => _isCore ??= IsCore();
private static bool IsCore()
{
PropertyInfo property = typeof(PowerShell)
.Assembly.GetType("System.Management.Automation.PSVersionInfo")
.GetProperty(
"PSVersion",
BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
return (Version)property.GetValue(property) is not { Major: 5, Minor: 1 };
}
public static string ReadGzip(string path)
{
if (IsCoreCLR)
{
return ReadGzipCore(path);
}
return ReadGzipFramework(path);
}
private static string ReadGzipFramework(string path)
{
int marker = 0;
int b;
using FileStream fs = File.OpenRead(path);
MemoryStream outmem = new();
while ((b = fs.ReadByte()) != -1)
{
if (marker == 0 && (byte)b == GzipPreamble1)
{
marker++;
continue;
}
if (marker == 1)
{
if ((byte)b == GzipPreamble2)
{
marker++;
continue;
}
marker = 0;
}
if (marker == 2)
{
marker = 0;
if ((byte)b == GzipPreamble3)
{
AppendBytes(path, outmem, fs.Position - 3);
}
}
}
outmem.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(outmem);
return reader.ReadToEnd();
}
private static void AppendBytes(string path, MemoryStream outmem, long pos)
{
using FileStream substream = File.OpenRead(path);
substream.Seek(pos, SeekOrigin.Begin);
using GZipStream gzip = new(substream, CompressionMode.Decompress);
gzip.CopyTo(outmem);
}
private static string ReadGzipCore(string path)
{
using FileStream fs = File.OpenRead(path);
using GZipStream gzip = new(fs, CompressionMode.Decompress);
using StreamReader reader = new(gzip);
return reader.ReadToEnd();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment