Gzip to String
String to Gzip
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/