blog.jj5.net (2003 to 2005)

Serialization Snippets

Fri Apr 9 08:37:00 UTC+1000 2004

Categories:

A while ago on some mailing list someone asked about serialization, and I responded with some sample code.

For some reason, I keep searching through my sent items for that code. Figured I might as well put it on my blog, it's easier for me to get at.

John.

> I am trying to serialize a local array of own classes.
>
> I wanted to do this by the public indexer. It looks like that
> is not possible.
>
> I'm doubting between two solutions:
>
> A Create a public property for the array.
>
> B Create a new class that will then have the array inside.
>
> What should I do?

If by local you simply mean you have a local array variable scoped inside a function you can serialize the array like this:

      string[] data = {"one", "two", "three"};
      using (FileStream stream = File.OpenWrite("c:\\temp.bin")) {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, data);
      }

If you mean you have a class like this:

  public class SomeClass {
   
    private string[] data;

    public string this[int i] {
      get { return this.data[i]; }
      set { this.data[i] = value; }
    }

    public SomeClass() {
      this.data = new string[] {"one", "two", "three"};
    }
  }

and you want to be able to serialize the 'data' variable that you can't access, then why wouldn't you make your container class serializable, like this:

  [Serializable]
  public class SomeClass : ISerializable {
   
    private string[] data;

    public string this[int i] {
      get { return this.data[i]; }
      set { this.data[i] = value; }
    }

    public SomeClass() {
      this.data = new string[] {"one", "two", "three"};
    }

    protected SomeClass(SerializationInfo info, StreamingContext context) {
      this.data = (string[])info.GetValue("data", typeof(string[]));
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context) {
      info.AddValue("data", this.data);
    }
  }

You could then just serialize your container class like this:

      SomeClass c = new SomeClass();
      using (FileStream stream = File.OpenWrite("c:\\temp.bin")) {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, c);
      }

and you can deserialize it like this:

      SomeClass c = null;
      using (FileStream stream = File.OpenRead("c:\\temp.bin")) {
        BinaryFormatter formatter = new BinaryFormatter();
        c = (SomeClass)formatter.Deserialize(stream);
      }

here's a hack that you can use to prove it deserialized:

      for (int i = 0; i < 3; i++) {
        MessageBox.Show(c[i]);
      }

You'll want to have these using clauses for the above code:

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

 


Copyright © 2003-2005 John Elliot