简体   繁体   English

将byte []数组转换为DataTable

[英]Convert a byte[] array into DataTable

I saved an object of type DataTable into SQL 2005 database in a field of type varbinary. 我在类型为varbinary的字段中将DataTable类型的对象保存到SQL 2005数据库中。 I want to retrieve it back but I wasn't able to type cast it. 我想要找回它,但我无法输入它。 This is how i saved it. 这就是我拯救它的方式。

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();

}

The 'dt' is the DataTable object instance. 'dt'是DataTable对象实例。

What your talking about is Binary Serialization and Deserialization. 你所说的是二进制序列化和反序列化。 Maybe this will help. 也许会有所帮助。

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();
        }
    }
}

I'm afraid I'll have to disappoint you, at least until you tell us that you've created an extension method for the StreamWriter class that handles data tables. 我担心我不得不让你失望,至少在你告诉我们你已经为处理数据表的StreamWriter类创建了一个扩展方法之前。

The only overload of the Write method that accepts a DataTable instance is the one that takes an object, and per the MSDN documentation , it only saves the "text representation" of the object. 接受DataTable实例的Write方法的唯一重载是获取对象的重载,并且根据MSDN文档 ,它只保存对象的“文本表示”。

So, let's hope that the .ToString method of DataTable outputs a string in a format that contains all the contents of the DataTable instance, but alas. 所以,我们希望DataTable的.ToString方法以包含DataTable实例的所有内容的格式输出一个字符串,但是唉。 The .ToString method only returns the contents of the TableName property , and a display expression, if one is present. .ToString方法仅返回TableName属性的内容 ,以及显示表达式(如果存在)。

So what you've saved is not the contents of the DataTable instance all, only the name of the table. 所以你保存的不是DataTable实例的全部内容,只是表的名称。

You should look into Serialization , it should be able to produce a binary or XML-representation of all the contents of the DataTable object. 您应该查看序列化 ,它应该能够生成DataTable对象的所有内容的二进制或XML表示。

I assume your code just serialized the data table and you have to deserialize it. 我假设您的代码只是序列化了数据表,您必须反序列化它。 I don't know what formatter was used, so you will have to look at the content of you binary field. 我不知道使用了什么格式化程序,因此您必须查看二进制字段的内容。 If it is binary, use the BinaryFormater (see the example code down the page). 如果是二进制文件,请使用BinaryFormater (请参阅页面中的示例代码)。 If it is not binary, try SoapFormatter and XmlSerializer . 如果它不是二进制文件,请尝试使用SoapFormatterXmlSerializer

You might be better off using XmlSerializer or BinaryFormatter to serialize your DataTable and then store in a binary column. 您可能最好使用XmlSerializer或BinaryFormatter来序列化DataTable,然后存储在二进制列中。

Links to do that: 这样做的链接:
http://sadeveloper.net/forums/p/439/1772.aspx http://sadeveloper.net/forums/p/439/1772.aspx
http://bytes.com/topic/net/answers/428472-serializing-datatable http://bytes.com/topic/net/answers/428472-serializing-datatable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM