Serialization of dataset in WebService is a common problem. However, if a large dataset is encountered, network transmission must be considered. It is a good choice to compress and transmit dataset, this method is provided as follows:
Step 1: Introduce the namespace to download the datasetsurrogate component
Using system. Io. compression;
Using system. runtime. serialization. formatters. Binary;
Put the downloaded datasetsurrogate in the bin path.
Step 2: compression serialization
/// Serialize the dataset converted to a binary array
Public byte [] getdatasetsurrogatezipbytes (Dataset DS)
{
Datasetsurrogate DSS = new datasetsurrogate (DS );
/// Serialized in binary mode
Binaryformatter SER = new binaryformatter ();
Memorystream MS = new memorystream ();
Ser. serialize (MS, DSS );
Byte [] buffer = Ms. toarray ();
/// Call the compression method
Byte [] zipbuffer = compress (buffer );
Return zipbuffer;
}
/// Compress binary files
Private byte [] compress (byte [] data)
{
Memorystream MS = new memorystream ();
Stream zipstream = NULL;
Zipstream = new gzipstream (MS, compressionmode. Compress, true );
/// Write the compressed bytes to the base stream from the specified byte array
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;
}
Part 3: Decompress deserialization
/// Decompress the compressed binary array
Public static byte [] decompress (byte [] data)
{// The data parameter is the compressed binary array
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;
/// Return the unzipped binary array
}
Catch
{
Return NULL;
}
}
/// Deserialize the binary file and convert it to 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;
}
This completes the operation.