I get exception when using serialize.

T

Tony Johansson

Hello!

I'm just testing the serialize and deserialize but I run into problem.

When method SaveBigThing is executing this statement
"fmt.Serialize(stream,thing);"
I get the following exception
"The type BigThing in Assembly ConsoleApplication23, Version=1.0.2419.32636,
Cult
ure=neutral, PublicKeyToken=null is not marked as serializable."

I can't understand what the problem is.

Hope somebody can see where the problem is?

//Source code
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class BigThing
{
public string namn = "Tony Johansson";
public string adress = "Båtvägen 47";
public int tel = 054521491;
}


public class myApp
{
private static BigThing thing = new BigThing();
private static BinaryFormatter fmt = new BinaryFormatter();

private static void SaveBigThing()
{
try
{
Stream stream = new
FileStream("sco.ser",FileMode.Create,
FileAccess.Write,FileShare.None);

fmt.Serialize(stream,thing);
stream.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}


private static void LoadBigThing()
{
Stream stream = new FileStream("sco.ser",FileMode.OpenOrCreate,
FileAccess.Read,FileShare.None);
thing = (BigThing)fmt.Deserialize(stream);
stream.Close();
}

[STAThread]
public static void Main(string[] args)
{
myApp.SaveBigThing();
thing.namn = ""; thing.adress = ""; thing.tel = 0;

myApp.LoadBigThing();
Console.WriteLine(thing.namn);
Console.WriteLine(thing.adress);
Console.WriteLine(thing.tel);
}
}

//Tony
 
C

Chris Dunaway

Tony said:
I'm just testing the serialize and deserialize but I run into problem.

When method SaveBigThing is executing this statement
"fmt.Serialize(stream,thing);"
I get the following exception
"The type BigThing in Assembly ConsoleApplication23, Version=1.0.2419.32636,
Cult
ure=neutral, PublicKeyToken=null is not marked as serializable."

I can't understand what the problem is.

The problem is pretty clearly stated: BigThing "is not marked as
serializable". To fix it, add the [Serializable] attribute to the
BigThing class:
//Source code
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class BigThing
{
public string namn = "Tony Johansson";
public string adress = "Båtvägen 47";
public int tel = 054521491;
}
 

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