Object serialization

765 palavras 4 páginas
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 of our 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 you by 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 which the 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; // Bring into 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 in Soap namespace

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

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

Relacionados

  • Teste killer scjp 5
    7238 palavras | 29 páginas
  • Heleder
    2684 palavras | 11 páginas
  • Desenvolvedor de sistemas junior
    70706 palavras | 283 páginas
  • Teste
    4298 palavras | 18 páginas
  • Redes
    5837 palavras | 24 páginas
  • Tecnologia
    3879 palavras | 16 páginas
  • Photoshop cs5
    3871 palavras | 16 páginas
  • Redes
    3871 palavras | 16 páginas
  • Memina co capoz vermelho
    3871 palavras | 16 páginas
  • Apostila de c# (programmers heaven)
    12889 palavras | 52 páginas