您的位置:首页 > 其它

在.Net Compact Framework 3.5中使用GZip

2015-10-27 17:11 274 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/allen6lu/article/details/84746856

在.Net Compact Framework 3.5中将数据加压

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace MRSDataSync.Helper
{
public class GZip
{
private Encoding encode = Encoding.UTF8;

public byte[] zipData(byte[] inputData)
{
if (inputData == null)
{
throw new ArgumentNullException("input data cannot be null.");
}

byte[] result;

#region MS compressor
MemoryStream mso = null;
try
{
mso = new MemoryStream();
GZipStream gzipStream = null;
try
{
gzipStream = new GZipStream(mso, CompressionMode.Compress, false);
gzipStream.Write(inputData, 0, inputData.Length);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
throw;
}
finally
{
if (gzipStream != null)
{
gzipStream.Close();
gzipStream.Dispose();
gzipStream = null;
}
}

result = mso.ToArray();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
throw;
}
finally
{
if (mso != null)
{
mso.Close();
mso.Dispose();
mso = null;
}
}

return result;
#endregion
}

public byte[] unZipData(byte[] inputData)
{
if (inputData == null)
{
throw new ArgumentNullException("input data cannot be null.");
}

byte[] result;

#region MS decompressor
MemoryStream msi = null;
MemoryStream mso = null;
try
{
msi = new MemoryStream(inputData);
mso = new MemoryStream();
GZipStream gzipStream = null;
try
{
gzipStream = new GZipStream(msi, CompressionMode.Decompress, false);
#region copy stream
const int BUFFER_SIZE = 4096;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = gzipStream.Read(buffer, 0, BUFFER_SIZE)) != 0)
{
mso.Write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
mso.Flush();
#endregion
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
throw;
}
finally
{
if (gzipStream != null)
{
gzipStream.Close();
gzipStream.Dispose();
gzipStream = null;
}
}

result = mso.ToArray();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
throw;
}
finally
{
if (msi != null)
{
msi.Close();
msi.Dispose();
msi = null;
}

if (mso != null)
{
mso.Close();
mso.Dispose();
mso = null;
}
}

return result;
#endregion
}

public byte[] zipStr2Data(string inputData)
{
byte[] strData = encode.GetBytes(inputData);
return zipData(strData);
}

public string unZipData2Str(byte[] inputdata)
{
byte[] outData = unZipData(inputdata);
return encode.GetString(outData, 0, outData.Length);
}
}
}

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: