当前位置:  开发笔记 > 编程语言 > 正文

将byte []数组转换为DataTable

如何解决《将byte[]数组转换为DataTable》经验,为你挑选了1个好方法。

我在类型为varbinary的字段中将DataTable类型的对象保存到SQL 2005数据库中.我想要找回它,但我无法输入它.这就是我拯救它的方式.

MemoryStream memStream = new MemoryStream();
    StreamWriter sw = new StreamWriter(memStream);

sw.Write(dt);
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Tables(TableName, TableData, QuestionID) VALUES (@TableName, @TableData, @QuestionID)", con))
{
    cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = "a new table";
    cmd.Parameters.Add("@TableData", SqlDbType.VarBinary,Int32.MaxValue).Value = memStream.GetBuffer();
    cmd.Parameters.Add("@QuestionID", SqlDbType.VarChar).Value = "2";
    cmd.ExecuteNonQuery();

}

'dt'是DataTable对象实例.



1> MyItchyChin..:

你所说的是二进制序列化和反序列化.也许这会有所帮助.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
using System.Text;

namespace Serial
{
    public class Ser
    {
        public static byte[] StrToByteArray(string str)
        {
            UTF8Encoding  encoding = new UTF8Encoding ();
            return encoding.GetBytes(str);
        }

        public static string ByteArrayToStr(byte[] barr)
        {
            UTF8Encoding  encoding = new UTF8Encoding ();
            return encoding.GetString(barr, 0, barr.Length);
        }

        public static void Main(String[] args)
        {
            DataTable dt = new DataTable();
            DataRow dr;

            dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
            dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
            dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("BooleanValue", typeof(bool)));

            for (int i = 1; i <= 1; i++) 
            {

                dr = dt.NewRow();

                dr[0] = i;
                dr[1] = "Item " + i.ToString();
                dr[2] = DateTime.Now;
                dr[3] = (i % 2 != 0) ? true : false;

                dt.Rows.Add(dr);
            }

            //Serialize
            BinaryFormatter bformatter = new BinaryFormatter();
            MemoryStream  stream = new MemoryStream();

            string s;
            bformatter.Serialize(stream, dt);
            byte[] b = stream.ToArray();
            s = ByteArrayToStr(b);
            stream.Close();
            dt = null;

            //Now deserialise
            bformatter = new BinaryFormatter();
            byte[] d;
            d = StrToByteArray(s);
            stream = new MemoryStream(d);
            dt = (DataTable)bformatter.Deserialize(stream);
            stream.Close();
        }
    }
}

推荐阅读
mobiledu2402851323
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有