GZipStream.Write Method



我已经阅读了一小段时间关于GZipStream及其Write方法。我正在尝试做的是从流中转换压缩数据并将其放在字节数组中。我将在下面为您提供我的代码,因为我相信它会有很大帮助。

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

与其写入磁盘上的文件,我想将压缩数据写入字节数组,然后返回字节数组(当然,假设我将其设置为函数)。

您可以

简单地使用"使用另一个MemoryStream及其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();
    }
}

来自我的一个扩展库

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

相关内容

  • 没有找到相关文章

最新更新