WebService中的DataSet序列化使用

服务端代码:

============================================================

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.Data.SqlClient;
using System.Runtime.Serialization.Formatters.Binary;
using CompressDataSet;
using System.IO;

namespace WebService1
{

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "获取DataSet,并进行操作")]
public bool BackUpUserTable(byte[] ds)
{
//获取用户传来的DataSet序列化 并反序列化
MemoryStream ms = new MemoryStream(ds);
BinaryFormatter bf = new BinaryFormatter();
Object o = bf.Deserialize(ms);
DataSetSurrogate dss = (DataSetSurrogate)o;
DataSet dataSet = dss.ConvertToDataSet();
//自定义操作内容
// ***
return false;
}
}
}

客户端代码:

================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CompressDataSet;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace WindowsClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

/// <summary>
/// 更新服务端数据库方法
/// </summary>
/// <param name="userName"></param>
public void UpdateInfo()
{
//封装DataSet
DataSet ds = new DataSet();
DataTable table = new DataTable();
table.Columns.Add("a");
table.Columns.Add("b");
table.Columns.Add("c");
for (int i = 0; i < 10; i++)
{
DataRow row = table.NewRow();
row["a"] = i.ToString() + "a";
row["b"] = i.ToString() + "b";
row["c"] = i.ToString() + "c";
}
//把DataSet序列化
DataSetSurrogate dss = new DataSetSurrogate(ds);
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, dss);
//把流装到数组里
byte[] io = ms.ToArray();
//调用WebService
ServiceReferenceUserService.Service1SoapClient userService = new WindowsClient.ServiceReferenceUserService.Service1SoapClient();

//操作
if (userService.BackUpUserTable(io))
{
MessageBox.Show("成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

原文地址:https://www.cnblogs.com/zhcw/p/2456558.html