代码如下:
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压缩类进行流压缩
/**/
/// <summary>
/// 压缩数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns> www.jb200.com
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;
}
/**/
/// <summary>
/// 解压数据
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
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
}