C# DataTable轉換byte

來源:互聯網
上載者:User

datatable 轉為byte[] 以及把byte[]轉為datatable 其實就是系列化與反系列的問題.實際上所有的類都可以使用byte[]形式表示,因為他在記憶體中的資料本身就是byte

而對於你說的String進行

System.Text.Encoding.BigEndianUnicode.GetBytes

System.Text.Encoding.Default.GetBytes    等等

這個除了此還有編碼讀取的功能,對於文本的編碼,沒有辦法,各個國家為了自己的文字儲存占更少空間都有各自的標準,對其它國家的文字就支援不好了,當然也有支援各國文字的utf-8等

第一種方法: 

請你參考一下,在vs 2008下運行 通過
引用命名空間
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

程式碼片段:

DataTable dt = new DataTable(); //用來轉成byte[]的執行個體
dt.Columns.Add("a");
dt.Rows.Add("b"); //添加一條測試資料 b
System.IO.MemoryStream memory = new MemoryStream();//使用記憶體流來存這些byte[]
BinaryFormatter b = new BinaryFormatter();
b.Serialize(memory,dt); //系列化datatable,MS已經對datatable實現了系列化介面,如果你自訂的類要系列化,實現IFormatter 就可以類似做法
byte[] buff = memory.GetBuffer(); //這裡就可你想要的byte[],可以使用它來傳輸
memory.Close();

//假如接收的仍是這個byte[] buff,這樣來反系列化

DataTable dt1 = (DataTable)b.Deserialize(new MemoryStream(buff)); //dt1是byte[]轉回的datatable
Response.Write(dt1.Rows[0][0].ToString());

//輸出的是 "b"

第二種方法

      MemoryStream memory = new MemoryStream();
      System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(memory, System.Text.Encoding.UTF8);

      dt.WriteXml(memory);
      int count = (int)memory.Length;
      byte[] temp = new byte[count];
      memory.Seek(0, SeekOrigin.Begin);
      memory.Read(temp, 0, count);
      string returnValue = Convert.ToBase64String(temp);
      return returnValue;

       讀取字串資訊
            byte[] bstr = Convert.FromBase64String(strType);
            System.Text.Encoding ed=System.Text.Encoding.UTF8;
            string returnValue = ed.GetString(bstr, 0, bstr.Length).Trim();

         //  把位元組轉換成datatable     

           MemoryStream ms=new MemoryStream(bstr);
           System.Xml.XmlTextReader xtw = new System.Xml.XmlTextReader(ms);
           ds.ReadXml(xtw);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.