WebService中Dataset的壓縮序列化和解壓還原序列化(DataSetSurrogate的使用)

來源:互聯網
上載者:User

在webservice中將dataset序列化是我們經常遇到的問題,但是遇到很大的dataset,則網路傳輸就必須考慮的問題,將dataset處理壓縮後傳輸是我們不錯的選擇,下面提供這種方法:

第一步:引入命名空間下載DataSetSurrogate組件

using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;

將下載好的DataSetSurrogate放入bin路徑下

第二步:壓縮序列化

///序列化轉化為位元組的DataSet

 public byte[] GetDataSetSurrogateZipBYtes(DataSet DS)
  {
        DataSetSurrogate dss = new DataSetSurrogate(DS);
        ///二進位方式方式序列化

        BinaryFormatter ser = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        ser.Serialize(ms, dss);
        byte[] buffer = ms.ToArray();
       ///調用壓縮方法

        byte[] Zipbuffer = Compress(buffer);
        return Zipbuffer;
  }

 ///壓縮二進位檔案
 private byte[] Compress(byte[] data)
  {
      MemoryStream ms = new MemoryStream();
      Stream zipStream = null;
      zipStream = new GZipStream(ms, CompressionMode.Compress, true);

       ///從指定的位元組數組中將壓縮的位元組寫入基礎流

      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;
   }

第三部:解壓還原序列化

///將壓縮後的位元組解壓

 public static byte[] Decompress(byte[] data)
  {      ///data參數為壓縮後的位元組
        try
        {
          MemoryStream ms = new MemoryStream(data);
          Stream zipStream = null;
          zipStream = new GZipStream(ms, CompressionMode.Decompress);
          byte[] dc_data = null;
          dc_data = EtractBytesFormStream(zipStream, data.Length);
          return dc_data;

          ///返回解壓後的位元組
         }
      catch
         {
             return null;
         }
  }

/// 將二進位檔案還原序列化後轉化為DataSet

  public DataSet GetDatasetFromByte(byte[] ZipByte)
  {
       byte[] buffer = UnZipClass.Decompress(ZipByte);
       BinaryFormatter ser = new BinaryFormatter();
       DataSetSurrogate dss;
       dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
       DataSet DS = dss.ConvertToDataSet();
       return DS;

   }

至此完成操作,歡迎指導。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.