不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
GZipStream压缩/解压字符串(C#)
编辑:dnawo 日期:2009-12-18
复制内容到剪贴板
程序代码

//using System.IO;
//using System.IO.Compression;
/// <summary>
/// GZipStream压缩字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public Stream GZipCompress(string str)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
MemoryStream msReturn;
using (MemoryStream msTemp = new MemoryStream())
{
using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, true))
{
gz.Write(buffer, 0, buffer.Length);
gz.Close();
msReturn = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length);
}
}
return msReturn;
}
/// <summary>
/// GZipStream解压字符串
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public string GZipDecompress(Stream stream)
{
byte[] buffer = new byte[100];
int length = 0;
using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
}
return System.Text.Encoding.UTF8.GetString(msTemp.ToArray());
}
}
}
//using System.IO.Compression;
/// <summary>
/// GZipStream压缩字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public Stream GZipCompress(string str)
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
MemoryStream msReturn;
using (MemoryStream msTemp = new MemoryStream())
{
using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, true))
{
gz.Write(buffer, 0, buffer.Length);
gz.Close();
msReturn = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length);
}
}
return msReturn;
}
/// <summary>
/// GZipStream解压字符串
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public string GZipDecompress(Stream stream)
{
byte[] buffer = new byte[100];
int length = 0;
using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
}
return System.Text.Encoding.UTF8.GetString(msTemp.ToArray());
}
}
}
说明
·压缩时GZipStream构造函数第三个参数一定要设置为true,并且一定要先调用Close再来复制,否则不能正常解压(测试发现调用Close后会追加几字节内容);
·解压时直接使用Read方法读取内容,不能调用GZipStream实例的Length等属性,否则会出错:System.NotSupportedException: 不支持此操作;
评论: 0 | 引用: 0 | 查看次数: 10060
发表评论
请登录后再发表评论!