使用CLR函式壓縮(Gzip)ntext型別欄位

kitesky發表於2012-08-29

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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章