Frage

I have been reading for a short while about GZipStream and its Write method. What I am attempting to do is convert the compressed data from the stream and put it in a byte array. I will leave you with my code below as I believe it 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);
    }
}

Rather than writing to a file on my disk, I would like to write the compressed data onto a byte array, and then return the byte array (assuming I made this a function of course).

War es hilfreich?

Lösung

You can simply use use another MemoryStream and its ToArray method.

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();
    }
}

Andere Tipps

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();
        }
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top