I am having a problems creating binary serialization for my observable collection of Contacts Objects. The Person Object contains the firstname,lastname, and age properties. The collection is called NewAccountList.
I want to be able to persist my collection data by saving it to a file. This action currently occurs when the save button is clicked, but it does xml serialization instead of binary serialization.
private void MenuItem_Click_2(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection)); sfd.Filter = "XML files (.xml)|.xml";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = sfd.ShowDialog();
try
{
using (StreamWriter wr = new StreamWriter("SavedAccounts.xml"))
{
xs.Serialize(wr, NewAccountList);
}
}
catch
{}
}
Would anybody be able to give me a good example of how to save a collection of objects?
full code example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (FileStream fs = File.Create("data.hffgfh"))
{
bf.Serialize(fs, 123456);
}
}
}
}
output:
