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
{
///
/// 功能:基于网络流传输的数据转换器
/// 作者:王昊昇
/// 时间:2012.11.8
///
internal static class NetDataConverter
{
///
/// 将字节数组转换为数据表
///
/// 字节数组
/// 数据表
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();
}
}
}
///
/// 将字节数组转换为数据表集合
///
/// 字节数组
/// 数据表集合
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;
}
}
///
/// 将字节数组转换为数据表集合
///
/// 内存流
/// 数据表集合
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;
}
///
/// 将数据表转换为字节数组
///
/// 数据表
/// 字节数组
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();
}
}
}
///
/// 将数据表集合转换为字节数组
///
/// 数据表集合
/// 字节数组
internal static byte[] DataSetToByteArray(DataSet dataSet)
{
//创建内存流
using (MemoryStream ms = new MemoryStream())
{
//将数据以xml方式写入流
dataSet.WriteXml(ms, XmlWriteMode.WriteSchema);
//返回字节数组
return ms.ToArray();
}
}
}
}