使用CLR函数压缩(Gzip)ntext类型字段

Gzip to String
String to Gzip

[@more@]

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

using System.IO;
using System.IO.Compression;
using System.Text;

public partial class Gzip
{

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlChars GzipToString(SqlBytes gBytes)
{
byte[] bytes = gBytes.Value;
bytes = Decompress(bytes);
string str = Encoding.GetEncoding(936).GetString(bytes);
SqlChars sqlchars = new SqlChars(str);
return (sqlchars);
}

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlBytes StringToGzip(SqlChars chars)
{


byte[] bytes = Encoding.GetEncoding(936).GetBytes(chars.Buffer);
bytes = Compress(bytes);
SqlBytes gBytes = new SqlBytes(bytes);

return (gBytes);
}


#region 采用.net系统自带Gzip压缩类进行流压缩
/**/
///
/// 压缩数据
///
///
///
public static byte[] Compress(byte[] data)
{
byte[] bData;
MemoryStream ms = new MemoryStream();
GZipStream stream = new GZipStream(ms, CompressionMode.Compress, true);
stream.Write(data, 0, data.Length);
stream.Close();
stream.Dispose();
//必须把stream流关闭才能返回ms流数据,不然数据会不完整
//并且解压缩方法stream.Read(buffer, 0, buffer.Length)时会返回0
bData = ms.ToArray();
ms.Close();
ms.Dispose();
return bData;
}

/**/
///
/// 解压数据
///
///
///
public static byte[] Decompress(byte[] data)
{
byte[] bData;
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
GZipStream stream = new GZipStream(ms, CompressionMode.Decompress, true);
byte[] buffer = new byte[1024];
MemoryStream temp = new MemoryStream();
int read = stream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
temp.Write(buffer, 0, read);
read = stream.Read(buffer, 0, buffer.Length);
}
//必须把stream流关闭才能返回ms流数据,不然数据会不完整
stream.Close();
stream.Dispose();
ms.Close();
ms.Dispose();
bData = temp.ToArray();
temp.Close();
temp.Dispose();
return bData;

}

#endregion
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/66009/viewspace-1059288/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/66009/viewspace-1059288/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值