zoukankan      html  css  js  c++  java
  • C#对GZIP压缩和解压

    /// <summary>
    /// 将Gzip的byte数组读取为字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static string ReadGzip(byte[] bytes, string encoding = "GB2312")
    {
        string result = string.Empty;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            using (GZipStream decompressedStream = new GZipStream(ms, CompressionMode.Decompress))
            {
                using (StreamReader sr = new StreamReader(decompressedStream, Encoding.GetEncoding(encoding)))
                {
                    result = sr.ReadToEnd();
                }
            }
        }
        return result;
    }
    
    /// <summary>
    /// 将字符串压缩成Gzip格式的byte数组
    /// </summary>
    /// <param name="str"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static byte[] WriteGzip(string str, string encoding = "GB2312")
    {
        byte[] rawData = System.Text.Encoding.UTF8.GetBytes(str);
        using (MemoryStream ms = new MemoryStream())
        {
            GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
            compressedzipStream.Write(rawData, 0, rawData.Length);
            compressedzipStream.Close();
            return ms.ToArray();
        }
    }
    
    /// <summary>
    /// 解压Gzip文件,返回字符串
    /// </summary>
    /// <param name="fileName">文件全路径</param>
    /// <returns>字符串</returns>
    public static string ReadGzipFromFile(string fileName)
    {
        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            using (GZipStream decompressedStream = new GZipStream(fileStream, CompressionMode.Decompress))
            {
                StreamReader reader = new StreamReader(decompressedStream);
                string result = reader.ReadToEnd();//重点
                reader.Close();
                return result;
            }
        }
    }

    外面可以通过File.ReadAllBytes()和File.WriteAllBytes()进行文件的操作。而GZIP文件的后缀名为.gz

    灵感来源:http://www.cnblogs.com/gengaixue/p/3300664.html

  • 相关阅读:
    Android WebService Does not support output
    textarea 内容对齐
    win7 下使用ssh连接vmare下的ubuntu系统
    myeclipse6.5 下无法使用tomcat7
    connectmongo.js 中出错 var Store = connect.session.Stroe
    linux tomcat7 ServerLifecycleListener类找不到
    SQL CASE 多条件用法
    myeclipse快捷键大全
    hibernat 中new对象进行查询
    SQL语句删除表中重复字段
  • 原文地址:https://www.cnblogs.com/duanjt/p/5715717.html
Copyright © 2011-2022 走看看