C# Tutorial - Serialize Objects to a File

来源:互联网 发布:拜占庭 推理 知乎 编辑:程序博客网 时间:2024/05/21 19:22

 

While storing information in memory is great, there comes a time your users will have to shut your application down. This means (probably) that you will need to write information to a file at some point, because you will want to store whatever data was in memory. Today, we are going to take a look at a feature built into .NET called Serialization that makes writing and reading data structures to and from a file extremely easy.

For this example, let's say I want to create a program that keeps track of all the cars my friends own. I'm going to create two objects to achieve this: Carand Owner. The Car object will store the make, model, and year of the car. The Owner object will save some information about who owns the car. EachCar object will hold a reference to an Owner object.

 

 

Since most of us have more than one friend, we're going to need to create a List of Car objects.

 

 

Now that we have our objects created, we're almost ready to serialize them. When I save data to files, I like to create an object specifically to hold all the things I want to serialize.

 

 

This class holds a reference to every object we'll want to serialize. In this case, the only thing we want to save is the list of cars. Now lets create the functions that will perform the serialization and deserialization of our object. I usually create a Serializer class to control the writing and reading to and from files.

 

 

As you can see, the actual code required to serialize an object is relatively small and simple. At this point, however, the code will not build. Before the Serialize function can be called on ObjectToSerialize we must include the Serializable attribute and it must implement the ISerializable interface.

 

 

As part of the ISerializable interface, the class must include another constructor for deserializing the object and a function GetObjectData which describes how to serialize the object. Since the Car and Owner objects are also being serialized, they will also need to implement these functions.

 

 

Now, to save the list of objects to a file, all that needs to be done is to call the Serialize and DeSerializefunctions of the Serializer class.

 

 

That is all that's required to save and load custom C# objects to a binary file. Just like any file, it is possible for your files to become corrupted. Because of this, it is probably a good idea to add some error handling whenever output from the file is being cast to an object.