Deserialize from MemoryStream cause Exception

P

Patricio Ogaz

Hi:

I try serielaze/deserialize a object using a MemoryStream in C#, but
this cause the exception "The root element its missing", when I try do
it whit a FileStream the exception not occur.

I need serialize in memory with XML (no write to a file), store this
information in a database and recover after to deserialize this XML.

The code for this (extract) it's:

THE CLASS:
[Serializable]
public class MyClass
{
private string sData = "";

public MyClass(){}

public string Data
{
get { return this.sData; }
set { this.sData = value; }
}
}

THE CODE IN CSHARP (Button in a WinForm):
private void button1_Click(object sender, System.EventArgs e)
{
try
{
/* Create objects instances */
MyClass MyObject = new MyClass();
MemoryStream oMStream = new MemoryStream();
SoapFormatter oSFormatter = new SoapFormatter();

/* Put Data to the object*/
MyObject.Data = "El valor de los valores";

/* Serialize MyObject into a memory stream */
oSFormatter.Serialize(oMStream,MyObject);

/*
* The next line cause the Exception
* "The root element its missing"
* */

/* Deserialize to a new object from the memory stream */
MyClass MyObject2 = (MyClass) oSFormatter.Deserialize(oMStream);

oMStream.Close();

MessageBox.Show(MyObject2.Data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}

Thank for your help !
 
J

Jon Skeet [C# MVP]

Patricio Ogaz said:
I try serielaze/deserialize a object using a MemoryStream in C#, but
this cause the exception "The root element its missing", when I try do
it whit a FileStream the exception not occur.

I need serialize in memory with XML (no write to a file), store this
information in a database and recover after to deserialize this XML.

/* Put Data to the object*/
MyObject.Data = "El valor de los valores";

/* Serialize MyObject into a memory stream */
oSFormatter.Serialize(oMStream,MyObject);

/*
* The next line cause the Exception
* "The root element its missing"
* */

/* Deserialize to a new object from the memory stream */
MyClass MyObject2 = (MyClass) oSFormatter.Deserialize(oMStream);

This is your problem bit. You're writing to the memory stream, but not
rewinding it to the beginning - so it's still at the end when you try
to deserialize. If you call oMStream.Position=0, it should be okay.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top