Serializzare un oggetto tramite ISerializable (SOAP)
L'oggetto da serializzare usando C#
I metodi per serializzare e deserializzare su Stream (FileStream in questo caso):
C#
[Serializable]
using System.Runtime.Serialization;
[Serializable]
public class Note : ISerializable
{
private string _title;
public string Title
{
get { return _title; }
set { _title = value; }
}
private string _body;
public string Body
{
get { return _body; }
set { _body = value; }
}
private int _version;
public int Version
{
get { return _version; }
set { _version = value; }
}
public Note()
{
}
//costruttore richiesto dalla serializzazione
protected Note(SerializationInfo info, StreamingContext context)
{
this.Title = info.GetString("MyTitle");
this.Body = info.GetString("MyBody");
this.Version = info.GetInt32("MyVersion");
}
// ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("MyTitle", this.Title);
info.AddValue("MyBody", this.Body);
info.AddValue("MyVersion", this.Version);
}
}
C#
Note note = new Note();
private const string FILENAME = "note.xml";
private void Deserialize()
{
if (File.Exists(FILENAME) == true)
{
SoapFormatter sf = new SoapFormatter();
using (Stream strm = File.Open(FILENAME, FileMode.Open))
{
if (strm.Length > 0)
{
try
{
//popola l'oggetto Note
note = (Note)sf.Deserialize(strm);
}
catch (System.Xml.XmlException ex)
{
//MessageBox.Show(ex.Message);
}
catch (System.Reflection.TargetInvocationException ex)
{
//nome elemento errato
}
}
}
}
}
private void Serialize()
{
SoapFormatter sf = new SoapFormatter();
using (Stream strm = File.Open(FILENAME, FileMode.Create, FileAccess.Write))
{
sf.Serialize(strm, note);
}
}
Aggiungere la referenza a System.Runtime.Serialization.Formatters.Soap.dll