Em có một InputStream từ file Upload
Và hàm chuyển Stream đó sang byte Array sau đó DeSerialize nó lại về DataTable như sau
Mã:
public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } public object ByteArrayToObject(byte[] _ByteArray) { try { // convert byte array to memory stream System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray); // create new BinaryFormatter System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); // System.Runtime.Serialization.Formatters.SoapMessage soap = new System.Runtime.Serialization.Formatters.SoapMessage(); // set memory stream position to starting point _MemoryStream.Position = 0; // Deserializes a stream into an object graph and return as a object. return _BinaryFormatter.Deserialize(_MemoryStream); // return soap. } catch (Exception _Exception) { // Error throw new Exception("Exception caught in process: {0}", _Exception.ToString()); } // Error occured, return null return null; }
Phần em gọi nó ra
Mã:
if (Request.Files.Count > 0) { string filename = ""; //Save file to server //filename = Request.Files[0].FileName.Split(System.IO.Path.DirectorySeparatorChar)[Request.Files[0].FileName.Split(System.IO.Path.DirectorySeparatorChar).Length - 1]; filename = Request.Files[0].FileName; //Request.Files[0].SaveAs(importFolder + filename); var bytearr = ReadFully(Request.Files[0].InputStream); DataTable dt =(DataTable) ByteArrayToObject((Byte[])bytearr);....}
Thì gặp lỗi này
"Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization."
E thấy mảng byte kia đã có giá trị nhưng ko hiểu sao ko thể DeSerialied được !
Mong các bác giúp đỡ ah
View more random threads:
Thông qua phân tích dữ liệu Google từ 86 quốc gia, mới đây, một công ty tại Anh đã công bố bảng xếp hạng kích tấc "cậu nhỏ" của các nước trên thế giới. Kết quả, hầu hết các nước xếp ở nhóm đầu của...
"Chim" của chàng trai Việt thuộc...