Problem converting a byte array into datatable.

Posted by kranthi on Stack Overflow See other posts from Stack Overflow or by kranthi
Published on 2010-05-21T09:35:36Z Indexed on 2010/05/21 9:40 UTC
Read the original article Hit count: 613

Filed under:
|
|

Hi,

In my aspx page I have a HTML inputfile type which allows user to browse for a spreadsheet.Once the user choses the file to upload I want to read the content of the spreadsheet and store the content into mysql database table.

I am using the following code to read the content of the uploaded file and convert it into a datatable in order into insert it into database table.

if (filMyFile.PostedFile != null)
        {
            // Get a reference to PostedFile object
            HttpPostedFile myFile = filMyFile.PostedFile;

            // Get size of uploaded file
            int nFileLen = myFile.ContentLength;

            // make sure the size of the file is > 0
            if (nFileLen > 0)
            {
                // Allocate a buffer for reading of the file
                byte[] myData = new byte[nFileLen];

                // Read uploaded file from the Stream
                myFile.InputStream.Read(myData, 0, nFileLen);

                DataTable dt = new DataTable();

               MemoryStream st = new MemoryStream(myData);
               st.Position = 0;
               System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
               dt=(DataTable)formatter.Deserialize(st);
}
}

But I am getting the following error when I am trying to deserialise the byte array into datatable.

Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.

Could someone please tell me what am I doing wrong?

I've also tried converting the bytearray into string ,then converting the string back to byte array and convert into datatable.That is also throwing the same error.

Thanks.

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about c#