天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

147 lines
4.4 KiB

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using Common.TextUtil;
using System.Reflection;
using Common.Exceptions;
namespace NSC
{
/// <summary>
/// 功能:基于网络流传输的数据转换器
/// 作者:王昊昇
/// 时间:2012.11.8
/// </summary>
internal static class NetDataConverter
{
/// <summary>
/// 将字节数组转换为数据表
/// </summary>
/// <param name="data">字节数组</param>
/// <returns>数据表</returns>
internal static DataTable ByteArrayToDataTable(byte[] data)
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(data, 0, data.Length);
ms.Position = 0;
System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, Encoding.GetEncoding("gb2312"));
xtw.WriteStartDocument();
//创建xml读取器
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(ms);
//创建数据集合
using (DataSet ds = new DataSet())
{
//将xml数据读入数据集合
ds.ReadXml(xtr, XmlReadMode.ReadSchema);
//返回数据集合
return ds.Tables[0].Copy();
}
}
}
/// <summary>
/// 将字节数组转换为数据表集合
/// </summary>
/// <param name="data">字节数组</param>
/// <returns>数据表集合</returns>
internal static DataSet ByteArrayToDataSet(byte[] data)
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(data, 0, data.Length);
ms.Position = 0;
System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, Encoding.GetEncoding("gb2312"));
xtw.WriteStartDocument();
//创建xml读取器
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(ms);
//创建数据集合
DataSet ds = new DataSet();
//将xml数据读入数据集合
ds.ReadXml(xtr, XmlReadMode.ReadSchema);
//返回数据集合
return ds;
}
}
/// <summary>
/// 将字节数组转换为数据表集合
/// </summary>
/// <param name="ms">内存流</param>
/// <returns>数据表集合</returns>
internal static DataSet MemoryStreamToDataSet(MemoryStream ms)
{
ms.Position = 0;
System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, Encoding.GetEncoding("gb2312"));
xtw.WriteStartDocument();
//创建xml读取器
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(ms);
//创建数据集合
DataSet ds = new DataSet();
//将xml数据读入数据集合
ds.ReadXml(xtr, XmlReadMode.ReadSchema);
//返回数据集合
return ds;
}
/// <summary>
/// 将数据表转换为字节数组
/// </summary>
/// <param name="table">数据表</param>
/// <returns>字节数组</returns>
internal static byte[] DataTableToByteArray(DataTable table)
{
using (DataSet ds = new DataSet())
{
ds.Tables.Add(table.Copy());
//创建内存流
using (MemoryStream ms = new MemoryStream())
{
//将数据以xml方式写入流
ds.WriteXml(ms, XmlWriteMode.WriteSchema);
//返回字节数组
return ms.ToArray();
}
}
}
/// <summary>
/// 将数据表集合转换为字节数组
/// </summary>
/// <param name="dataSet">数据表集合</param>
/// <returns>字节数组</returns>
internal static byte[] DataSetToByteArray(DataSet dataSet)
{
//创建内存流
using (MemoryStream ms = new MemoryStream())
{
//将数据以xml方式写入流
dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);
//返回字节数组
return ms.ToArray();
}
}
}
}