I have a C# WinForms app containing a ListBox
control, which I populate with objects of type BukkitServer
. When an object is added or removed from the list, I want to write them to an XML file. I have a static method in a helper class that takes an ICollection
argument and achieves this.
However, since the ListBox.ObjectCollection
class is not serializable (fittingly, since it contains elements of type object
), I wrote a helper method to convert it to a List<BukkitServer>
.
It feels like a hack, though, and I feel (hope) there is a cleaner answer.
Any other comments and criticisms are welcome as well.
static class BukkitServerDataWriter {
public static void SaveServers(ICollection objects) {
using (XmlTextWriter writer = new XmlTextWriter("servers.xml", Encoding.UTF8)) {
XmlSerializer xml = new XmlSerializer(
typeof(List<BukkitServer>),
new Type[] { typeof(BukkitServer) });
List<BukkitServer> servers = MakeBukkitServerList(objects);
xml.Serialize(writer, servers);
}
}
private static List<BukkitServer> MakeBukkitServerList(ICollection collection) {
List<BukkitServer> servers = new List<BukkitServer>();
foreach (object obj in collection) {
servers.Add((BukkitServer)obj);
}
return servers;
}
}