Carlsberg
Carlsberg

Reputation: 709

Is it possible to save arbitrary data to a file in C#?

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?

Upvotes: 1

Views: 258

Answers (3)

Ahmed
Ahmed

Reputation: 7238

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;
}
}

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158319

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.

Upvotes: 4

Ilya Khaprov
Ilya Khaprov

Reputation: 2524

use BinaryFormatter to serialize the instance

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

Upvotes: 1

Related Questions