views:

74

answers:

3

I have a class with many collections loaded in memory. Is it possible to some how save this class with all its data to a file to be able to simply reload it to memory later? Is there an interface that would handle all this?

+1  A: 

use BinaryFormatter to serialize the instance

And add the [Serializable] attribute in front of the class definition

Trickster
+4  A: 

What you are describing is called serialization. You searialize an object into some data format that you can store on disk, and then you can later deserialize that data into an object. There are many ways of doing this, but the first step will be to make your class serializable, by adding the Serializable attribute:

[Serializable]
public class YourClass
{    
    // the class goes here
}

Then you can use for instance the XmlSerializer class to handle the serialization/deserialization.

Update
I should mention that you can use XmlSerializer even if your class is not decorated with the Serializable attribute. However, some other serialization mechanisms do require the attribute.

Fredrik Mörk
xml serialization of Dictionary<T, T1> is the easiest thing ever!
Trickster
A: 

You can use .Net Serialization facility, just you have to mark your class with [Serializable] attribute and all members should be also serializable

Sample code:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
class A
{
public static void Serialize(object obj,string filepath)
{
Formatter f = new BinaryFormatter();
f.Serialize(new FileStream(filepath,FileMode.Create),obj);
}
public static A Deserialize(string filepath)
{
Formatter f = new BinaryFormatter();
return  f.Deserialize(new FileStream(filepath, FileMode.Open)) as A;
}
}
Ahmed Said