C#GZip文字列の圧縮と解凍
10616 ワード
public class CGZipUtil
{
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static DataSet GetDatasetByString(string Value)
{
DataSet ds = new DataSet();
string CC = GZipDecompressString(Value);
System.IO.StringReader Sr = new StringReader(CC);
ds.ReadXml(Sr);
return ds;
}
/// <summary>
/// DATASET
/// </summary>
/// <param name="ds"></param>
/// <returns></returns>
public static string GetStringByDataset(string ds)
{
return GZipCompressString(ds);
}
/// <summary>
/// GZip , Base64
/// </summary>
/// <param name="rawString"> </param>
/// <returns> Base64 </returns>
public static string GZipCompressString(string rawString)
{
if (string.IsNullOrEmpty(rawString) || rawString.Length == 0)
{
return "";
}
else
{
byte[] rawData = System.Text.Encoding.UTF8.GetBytes(rawString.ToString());
byte[] zippedData = Compress(rawData);
return (string)(Convert.ToBase64String(zippedData));
}
}
/// <summary>
/// GZip
/// </summary>
/// <param name="rawData"></param>
/// <returns></returns>
static byte[] Compress(byte[] rawData)
{
MemoryStream ms = new MemoryStream();
GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
compressedzipStream.Write(rawData, 0, rawData.Length);
compressedzipStream.Close();
return ms.ToArray();
}
/// <summary>
/// GZip
/// </summary>
/// <param name="zippedString"> GZip </param>
/// <returns> </returns>
public static string GZipDecompressString(string zippedString)
{
if (string.IsNullOrEmpty(zippedString) || zippedString.Length == 0)
{
return "";
}
else
{
byte[] zippedData = Convert.FromBase64String(zippedString.ToString());
return (string)(System.Text.Encoding.UTF8.GetString(Decompress(zippedData)));
}
}
/// <summary>
/// ZIP
/// </summary>
/// <param name="zippedData"></param>
/// <returns></returns>
public static byte[] Decompress(byte[] zippedData)
{
MemoryStream ms = new MemoryStream(zippedData);
GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream outBuffer = new MemoryStream();
byte[] block = new byte[1024];
while (true)
{
int bytesRead = compressedzipStream.Read(block, 0, block.Length);
if (bytesRead <= 0)
break;
else
outBuffer.Write(block, 0, bytesRead);
}
compressedzipStream.Close();
return outBuffer.ToArray();
}
}