VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之Gzip压缩和解压

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// <summary>
/// 将传入字符串以GZip算法压缩后,返回Base64编码字符
/// </summary>
/// <param name="rawString">需要压缩的字符串</param>
/// <returns>压缩后的Base64编码的字符串</returns>
public string GZipCompressString(string rawString)
{
    if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
    {
        return "";
    }
    else
    {
        byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
        byte[] zippedData = Compress(rawData);
        return (string)(Convert.ToBase64String(zippedData));
    }
}
 
/// <summary>
/// GZip压缩
/// </summary>
/// <param name="rawData"></param>
/// <returns></returns>
static byte[] Compress(byte[] rawData)
{
    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="zippedString">经GZip压缩后的二进制字符串</param>
/// <returns>原始未压缩字符串</returns>
public static string GZipDecompressString(string zippedString)
{
    if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
    {
        return "";
    }
    else
    {
        byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
        using (var ms = new MemoryStream(zippedData))
        {
            using (var zip = new GZipStream(ms, CompressionMode.Decompress))
            {
                using (var reader = new StreamReader(zip))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}

相关教程