| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Data;
- using System.Runtime.Serialization;
- namespace Core.Mes.Common
- {
- public class Utility
- {
- #region dataset to byte[]
- /// <summary>
- ///
- /// </summary>
- /// <param name="ds"></param>
- /// <returns></returns>
- public static byte[] SerializeDataSet(DataSet ds)
- {
- byte[] buffer = null;
- ds.RemotingFormat = SerializationFormat.Binary;
- MemoryStream ms = new MemoryStream();
- IFormatter bf = new BinaryFormatter();
- bf.Serialize(ms, ds);
- buffer = ms.ToArray();
- ms.Close();
- ms.Dispose();
- ms = null;
- ds.Dispose();
- ds = null;
- return buffer;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="buffer"></param>
- /// <returns></returns>
- public static DataSet ReSerializable(byte[] buffer)
- {
- MemoryStream ms = new MemoryStream(buffer);
- IFormatter bf = new BinaryFormatter();
- object obj = bf.Deserialize(ms);
- DataSet ds = (DataSet)obj;
- ms.Close();
- ms.Dispose();
- return ds;
- }
- #endregion
- #region 压缩、解压缩
- /// <summary>
- /// 压缩
- /// </summary>
- /// <param name="data"></param>
- /// <returns></returns>
- public static byte[] Compress(byte[] data)
- {
- MemoryStream ms = new MemoryStream();
- Stream zipStream = null;
- zipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true);
- //System.IO.Compression.CompressionMode:指定是否压缩和解压缩基础流(Compress:压缩,DeCompress:解压缩)
- zipStream.Write(data, 0, data.Length);
- zipStream.Close();
- ms.Position = 0;//获取或设置流中当前位置
- byte[] compressed_data = new byte[ms.Length];
- ms.Read(compressed_data, 0, int.Parse(ms.Length.ToString()));
- return compressed_data;
- }
- /// <summary>
- /// 解压缩
- /// </summary>
- /// <param name="data"></param>
- /// <returns></returns>
- public static byte[] Decompress(byte[] data)
- {
- try
- {
- MemoryStream ms = new MemoryStream(data);
- Stream zipStream = null;
- zipStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
- byte[] dc_data = null;
- dc_data = EtractBytesFormStream(zipStream, data.Length);
- return dc_data;
- }
- catch
- {
- return null;
- }
- }
- public static byte[] EtractBytesFormStream(Stream zipStream, int dataBlock)
- {
- try
- {
- byte[] data = null;
- int totalBytesRead = 0;
- while (true)
- {
- Array.Resize(ref data, totalBytesRead + dataBlock + 1);
- int bytesRead = zipStream.Read(data, totalBytesRead, dataBlock);
- if (bytesRead == 0)
- {
- break;
- }
- totalBytesRead += bytesRead;
- }
- Array.Resize(ref data, totalBytesRead);
- return data;
- }
- catch
- {
- return null;
- }
- }
- #endregion
- }
- }
|