• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 696
  • Last Modified:

ASP.NET - object serialization/deserialization

I've got the following code which is taking an object called 'history' of type Stack<String>, serializing it and placing it into a hidden textbox on a page.

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            formatter.Serialize(stream, history);
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);
            txtHistorySerialized.Text = reader.ReadToEnd();

The page is then posted to another page where the following code is being used to attempt to deserialize that object back into a Stack<String> so that it can be utilized.

            Stack<string> hist;
            if (Request["history"] != null)
            {
                String str = Request["history"].ToString();
                byte[] byteArray = Encoding.ASCII.GetBytes(str);
                MemoryStream stream = new MemoryStream(byteArray);
                IFormatter formatter = new BinaryFormatter();
                hist = formatter.Deserialize(stream) as Stack<string>;
            }

However, when the program execution comes to the line where the deserialize method is called, it throws an exception saying:

The input stream is not a valid binary format. The starting contents (in bytes) are: 01-3F-3F-3F-3F-01-0C-02-49-53-79-73-74-65-6D-2C-20 ...

Can anyone help me out on this and let me know where I'm messing up?

Thanks
0
josephdaviskcrm
Asked:
josephdaviskcrm
  • 3
  • 2
  • 2
  • +1
1 Solution
 
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
Hi,

You are saving your serialized data in txtHistorySerialized and while on deserialization you are trying to deserialize data of history from line String str =  Request["history"].ToString(); & that is why you are getting error The input stream is  not a valid binary format.

Regards,
VSS
0
 
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
Hi,

You need to use the binary data in txtHistorySerialized. I think then after it would work fine.

Regards,
VSS
0
 
Meir RivkinFull stack Software EngineerCommented:
need a little tweak: IFormatter formatter = new BinaryFormatter();            Stream stream = new MemoryStream();            formatter.Serialize(stream, new List(history.ToArray()));            stream.Position = 0;            StreamReader reader = new StreamReader(stream);            txtHistorySerialized.Text = reader.ReadToEnd();Stack hist;            if (Request["history"] != null)            {                String str = Request["history"].ToString();                byte[] byteArray = Encoding.ASCII.GetBytes(str);                MemoryStream stream = new MemoryStream(byteArray);                IFormatter formatter = new BinaryFormatter();                hist = new Stack((IEnumerable)formatter.Deserialize(stream));            }
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Meir RivkinFull stack Software EngineerCommented:
change:formatter.Serialize(stream, new List(history.ToArray()));to:formatter.Serialize(stream, new List(history));
0
 
josephdaviskcrmAuthor Commented:
sedgwick,
I'm still getting the same error I was before when I use your code.

vs00saini,
Your statement about needing to use binary data sounds great but I don't know how to do that.
0
 
Carl TawnSystems and Integration DeveloperCommented:
The problem is stemming from the way you are writing the data out in the first place. Simply trying to convert binary to a string and back again is going to cause all sorts of problems.

If you convert to a Base64 string on the way out then it will be a lot easier to read back:
/*
 *   write out
 */
Stack<string> stack = new Stack<string>();
stack.Push("Hello world");

IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, stack);

stream.Position = 0;
txtHistorySerialized.Text = Convert.ToBase64String(stream.GetBuffer());    // conver to Base64

/*
 *   Read back
 */
string source = Request["history"];
byte[] data = Convert.FromBase64String(source);

IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream ms = new MemoryStream(data);

Stack<string> history = (Stack<string>)formatter.Deserialize(ms);

Open in new window

0
 
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
Hi,

What I have learnt from programming till date about Serialization is that to Deserialize an object you should have the object of same type for which you have done serialization.

So here is the code for which you can test the code given here. The code is been developed in Window app but it can be converted into Web Application with little modification.

I have used two buttons on Form.

Please see the code attach.

Regards,
VSS

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

namespace ee_DataSerialization
{
    public partial class Form1 : Form
    {
        Stack<string> history;
        Stream stream;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            history = new Stack<string>();
            history.Push("Hello");           

            IFormatter formatter = new BinaryFormatter();
            stream = new MemoryStream();
            formatter.Serialize(stream, history);           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stack<string> hist;
            if (history!= null)
            {
                IFormatter formatter = new BinaryFormatter();
                stream.Position = 0;
                hist = formatter.Deserialize(stream) as Stack<string>;
                richTextBox1.Text = hist.Pop().ToString();
            }
        }
    }
}

Open in new window

0
 
josephdaviskcrmAuthor Commented:
The conversion to base64 string and back again was all I needed to do to make my code work perfectly.  Thanks for this.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now