How to serialize an object which is NOT marked as 'Serializable' using a surrogate.
C# Tutorial - Serialize Objects to a File
Serialization in C#
Object Serialization using C#
Sample code - will serialize class with child classes that are not explicitly serializable. (Work in progress though).
SurrogateSelector ss = new SurrogateSelector();
PicasaAlbumAccessorSurrogate aass = new PicasaAlbumAccessorSurrogate();
PicasaEntrySurrogate pess = new PicasaEntrySurrogate();
PicasaFeedSurrogate pfss = new PicasaFeedSurrogate();
ss.AddSurrogate(typeof(AlbumAccessor),
new StreamingContext(StreamingContextStates.All), aass);
ss.AddSurrogate(typeof(PicasaEntry),
new StreamingContext(StreamingContextStates.All), pess);
ss.AddSurrogate(typeof(PicasaFeed),
new StreamingContext(StreamingContextStates.All), pfss);
BinaryFormatter formatter = new BinaryFormatter();
string filename = string.Format("{0}\\album_{1}_{2}_{3}.dat",
System.Environment.CurrentDirectory, _accessor.AlbumAuthor,
_accessor.Name, _accessor.Id);
FileStream fs = new FileStream(filename, FileMode.Create);
formatter.SurrogateSelector = ss;
formatter.Serialize(fs, this);
fs.Close();
No comments:
Post a Comment