I have a class, see below, and I want to provide methods to Save/Load the class to disk using XML serialization.
I got the Save portion working, but I am having issues with the Load. I am not quite sure how to have a class deserialize itself.
The main application will create an instance of the CSLInfo class and call the Save/Load methods at various points.
To save data I would do the following:
And to load data I would do the following:Code:CSLInfo csl = new CSLInfo(); csl.Sites.Add(new Site("Customer1", "customer1", true)); csl.Sites.Add(new Site("Customer2", "customer2", false)); csl.Save();
I would like the Load method to read the xml file from disk and populate the csl variable with the data. I'm not sure if this even possible though.Code:CSLInfo csl = new CSLInfo(); csl.Load();
Also, I read up on implementing ISerializable, but I think I'd have to manually load all the data using ISerializable.GetObjectData, but that's more work than I want to put into this small application.
My final option would be to move the serialization/deserialization code to methods in the main application.
Any input on this would be appreciated.
Thanks,
CT
==== MY CLASS
Code:using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization; namespace Sandbox { [Serializable] public class CSLInfo { public CSLInfo() { } List<Site> _sites = new List<Site>(); public List<Site> Sites { get { return _sites; } set { _sites = value; } } public void Load() { } public void Save() { Stream s = null; try { s = File.Create(@"csl.xml"); XmlSerializer serial = new XmlSerializer(typeof(CSLInfo)); serial.Serialize(s, this); } finally { if (s != null) s.Dispose(); } } } public class Site { private string _customerName = ""; private string _dbName = ""; private bool _hasWebsite = false; public Site() { } public Site(string customerName, string databaseName, bool hasWebsite) { _customerName = customerName; _dbName = databaseName; _hasWebsite = hasWebsite; } public string CustomerName { get { return _customerName; } set { _customerName = value; } } public string DatabaseName { get { return _dbName; } set { _dbName = value; } } public bool HasWebsite { get { return _hasWebsite; } set { _hasWebsite = value; } } } }




Reply With Quote