在.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); } } }