Object serialization

Disponível somente no TrabalhosFeitos
  • Páginas : 4 (765 palavras )
  • Download(s) : 0
  • Publicado : 31 de maio de 2012
Ler documento completo
Amostra do texto
Serializing and Deserializing objects
Sometimes you need to persist information between runs of your program or for transportation.To do this task we have some classes that do the serialization ofour objects in the .NET framework, some of them are: BinaryFormatter and SoapFormatter, you can use these two classes to serialize/deserialize objects into binary or soap formats, respectively.These classes can serialize a simple object, or a complex type, that has references to another objects.

In this tutorial I’ll use the soap format( but it’s equivalent in the binary format ).Serializing a simple object
Well, to serialize an object, you need to create an SoapFormatter object, like this:

SoapFormatter soap = new SoapFormatter()
view rawgistfile1.csThis Gist brought to youby GitHub.
The SoapFormatter class is in System.Runtime.Serialization.Formatters.Soap namespace and you need to add a reference to the assembly.

The SoapFormatter class exposes two methods,Serialize and Deserialize.The Serialize method gets two arguments, an stream to which the object will be sent, and the object itself.The Deserialize method gets just one argument, the Stream from whichthe object will be read and Deserialized.

In the following examples we will serialize a string and send it to a file and after open the file a deserialize the string:

using System; // Bringinto scope all types in System namespace
using System.IO; // Bring into scope all types in System.IO namespace
using System.Runtime.Serialization.Formatters.Soap; // Bring into scope all types inSoap namespace

// Declare Test namespace
namespace Test
// Declare Program class
public class Program
// Declare Main(entry-point) method {static}
public staticvoid Main()
string txt = "The serialized string.";

using (FileStream file = File.Open("object.dat", FileMode.CreateNew, FileAccess.Write))
tracking img