webservice代码部分
[WebMethod(Description="直接返回DataSet对象")]
public DataSet GetDataSet()
{
//http://www.dzbsoft.com XT_TEXT
string sql = "select * from XT_TEXT";
SqlConnection conn = new SqlConnection("Server=60.28.25.58;DataBase=s168593;user id=s168593;password=h0y+FeC*;");
conn.Open();
SqlDataAdapter dataAd = new SqlDataAdapter(sql, conn);
DataSet DS = new DataSet("XT_TEXT");
dataAd.Fill(DS);
conn.Close();
return DS;
}
//Description 提示的关键字
[WebMethod(Description = "返回DataSetSurrogate对象用Binary序列化并ZIP压缩后的字节数组")]
public byte[] GetDataSetSurrogateZipBytes()
{
//获取Dataset对象
DataSet DS = GetDataSet();
// DataSetSurrogate微软的一个组件(将dataset填充到DataSetSurrogate对象中)
DataSetSurrogate dss = new DataSetSurrogate(DS);
//实例化一个二进制对象
BinaryFormatter ser = new BinaryFormatter();
//实例化一个内存流对象
MemoryStream ms = new MemoryStream();
//将DataSetSurrogate对象序列化,填充到内存流对象中
ser.Serialize(ms, dss);
//将字节流转化为数组放到byte数组中
byte[] buffer = ms.ToArray();
//将字节zip压缩后放在字节数组中
byte[] Zipbuffer = Compress(buffer);
return Zipbuffer;
}
public byte[] Compress(byte[] data)
{
//实例化一个内存流对象
MemoryStream ms = new MemoryStream();
//实例化一个流对象
Stream zipStream = null;
//GZipStream提供用于压缩和解压缩流的方法和属性。
//CompressionMode.Compress表示压缩
ms创建一个压缩流
zipStream = new GZipStream(ms, CompressionMode.Compress, true);
//将data中的字节流写入该流中
zipStream.Write(data, 0, data.Length);
///关闭该流
zipStream.Close();
//将内存流的位置指向开 始
ms.Position = 0;
//声明一个内存流长度的字节数组
byte[] compressed_data = new byte[ms.Length];
//从当前流中读取字节流写入compressed_data 中
ms.Read(compressed_data, 0, int.Parse(ms.Length.ToString()));
return compressed_data;
}
webservice调用的代码
private void button4_Click(object sender, EventArgs e)
{
//实例化webservice对象
com.dzbsoft.www.DataSetService ds = new Test.com.dzbsoft.www.DataSetService();
DateTime dtBegin = DateTime.Now;
// 获取webservice返回的序列化并压缩后的字节里数组
byte[] zipBuffer = ds.GetDataSetSurrogateZipBytes();
//将字节流数组解压缩
byte[] buffer = UnZipClass.Decompress(zipBuffer);
//实例化一个序列化对象
BinaryFormatter ser = new BinaryFormatter();
// 获取dataset
DataSet DS = ds.GetDataSet();
// 将字节流转化为内存流,然后进行反序列化,最后强制转化为DataSetSurrogate类型
DataSetSurrogate dss = ser.Deserialize(new MemoryStream(buffer)) as DataSetSurrogate;
//DataSetSurrogate转化为Dataset对象
DataSet dataset = dss.ConvertToDataSet();
this.label4.Text = string.Format("耗时:{0}", DateTime.Now - dtBegin + " " + zipBuffer.Length.ToString());
//绑定数据控件
BindDataSet(DS);
}
原文地址:http://shifengpsw.blog.163.com/blog/static/396074232009119113238161/