GZipStream.Write Method

I read a little about GZipStreamand method Write. What I'm trying to do is convert the compressed data from a stream and put it in an array of bytes. I will leave you with my code below, as I believe this will help significantly.

public static void Compress(byte[] fi)
{
    using (MemoryStream inFile = new MemoryStream(fi))
    using (FileStream outFile = File.Create(@"C:\Compressed.exe"))
    using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
    {
        inFile.CopyTo(Compress);
    }
}

Instead of writing to a file on my disk, I would like to write the compressed data to an array of bytes, and then return an array of bytes (suppose I made this a function, of course).

+5
source share
2 answers

You can simply use the other MemoryStreamand its method ToArray.

public static byte[] Compress(byte[] fi)
{
    using (MemoryStream outFile = new MemoryStream())
    {
        using (MemoryStream inFile = new MemoryStream(fi))
        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
        {
            inFile.CopyTo(Compress);
        }
        return outFile.ToArray();
    }
}
+6
source

From one of my extension libraries

public static string Compress(this string s)
    {
        byte[] bytesToEncode = Encoding.UTF8.GetBytes(s);
        return Convert.ToBase64String(bytesToEncode.Compress());
    }

    public static byte[] Compress(this byte[] bytesToEncode)
    {
        using (MemoryStream input = new MemoryStream(bytesToEncode))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress))
            {
                input.CopyTo(zip);
            }
            return output.ToArray();
        }
    }

    public static string Explode(this string s)
    {
        byte[] compressedBytes = Convert.FromBase64String(s);
        return Encoding.UTF8.GetString(compressedBytes.Explode());
    }

    public static byte[] Explode(this byte[] compressedBytes)
    {
        using (MemoryStream input = new MemoryStream(compressedBytes))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
            {
                zip.CopyTo(output);
            }
            return output.ToArray();
        }
    }
+3
source