Save List with BinaryReader
-
I have a class that has a list of objects. Since it doesn´t seem to work with xmlSerializer I´m trying to save to a binaryfile instead. When I use BinaryReader I read a string using ReadString but can I read a List or an object?
Fisrt off, you should easily be able to serialise a List with XMLSerializer, you just need to ensure that Your custom class is marked with the XmlRoot attribute, and you create a class that inherits from List that holds your collection, something like this
[XmlRoot("Persons")]
public class People : List<Person>
{}
[XmlRoot("Person")]
public class Person
{
public Person()
{
}public Person(string name) { Name = name; } \[XmlElement("Name")\] public string Name { get; set; }
}
then you can use this
using (StringWriter writer = new StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof(Persons));
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlWriter xmlWriter = XmlWriter.Create(writer, settings);
serializer.Serialize(xmlWriter, personList, namespaces);
}or something to that effect, and this should work to serialize to XML. If you still want to serialize to a binary file, you should use a BinaryFormatter like this
using (Stream stream = File.Open("people.bin", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, People);
}and deserialise also using a BinaryFormatter
using (Stream stream = File.Open("people.bin", FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var people = (List<Person>)bin.Deserialize(stream);
}Hope this helps
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman