title: Store and retrieve data table into Varbinary column
body: <p>For some reason I had to store a DataTable variable in a <code>Varbinary</code> column of a SQL Server table, but I get errors.</p>
  <p>This is store code:</p>
  <pre><code>// Read DataTable to Byte array
  DataTable dtgrd = new DataTable();
  DataAccess ds = new DataAccess();
  DataSet dst = new DataSet();
  dst.Tables.Add(dtgrd);
  
  string xmlString = dst.GetXml();
  MemoryStream ms = new MemoryStream();
  XmlDocument xml = new XmlDocument();
  xml.LoadXml(xmlString);
  xml.Save(ms);
  
  byte[] xmlBytes = ms.ToArray();
  
  // Store DataTable into database
  SqlConnection CN = new SqlConnection(Global.cs);
  string str = @&quot;INSERT INTO...... &quot;;
  
  SqlCommand SqlCom = new SqlCommand(str, CN);
  SqlCom.Parameters.Add(new SqlParameter(&quot;@FKDocInReqID&quot;, FKDocInReqID));
  SqlCom.Parameters.Add(new SqlParameter(&quot;@value&quot;, (object)xmlBytes));
  SqlCom.Parameters.Add(new SqlParameter(&quot;@Data&quot;, ReportTitle));
  SqlCom.Parameters.Add(new SqlParameter(&quot;@DocUploadUser_secuserID&quot;, Global.S_UserID));
  
  CN.Open();
  decimal id =(decimal) SqlCom.ExecuteScalar();
  CN.Close();
  </code></pre>
  <p>The store code has worked correctly and in the database, the columns has the proper bytes.</p>
  <p>But the retrieve code does not work:</p>
  <pre><code> string s = @&quot;select * from .... where id={0} &quot;;
   s = string.Format(s, id);
  
   DataTable dt = new DataTable();
   dt = ds.doSelect(s);
  
   using (System.IO.MemoryStream memStream1 = new System.IO.MemoryStream((byte[])dt.Rows[0][&quot;Value&quot;]))
   {
       dataGridView1.DataSource = FromBytes(memStream1.ToArray());
       dataGridView1.Refresh();
       dataGridView1.Show();
   }
  </code></pre>
  <p>and</p>
  <pre><code>static DataTable FromBytes(byte[] arr)
      {
          using (var ms = new MemoryStream(arr))
          {
              return (DataTable)new BinaryFormatter().Deserialize(ms);//**ERROR Raised Here**
          }
      }
  static byte[] ToBytes(DataTable table)
      {
          using (var ms = new MemoryStream())
          {
              table.RemotingFormat = SerializationFormat.Binary;
              new BinaryFormatter().Serialize(ms, table);
              return ms.ToArray();
          }
      }
  </code></pre>
  <p>this error is raised:</p>
  <p><a href="https://i.stack.imgur.com/quBWL.png" rel="nofollow noreferrer">error message</a></p>