[英]Binary Serialization of an Observable Collection — Saving, Loading
I am having a problems creating binary serialization for my observable collection of Contacts Objects. 我在为可观察到的Contacts对象集合创建二进制序列化时遇到问题。 The Person Object contains the firstname,lastname, and age properties.
Person对象包含名字,姓氏和年龄属性。 The collection is called NewAccountList .
该集合称为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.
单击保存按钮时,当前会发生此操作,但它会执行xml序列化而不是二进制序列化。
private void MenuItem_Click_2(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); 私人无效MenuItem_Click_2(对象发送者,RoutedEventArgs e){//创建OpenFileDialog Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection));
XmlSerializer xs =新的XmlSerializer(typeof(ObservableCollection)); sfd.Filter = "XML files ( .xml)| .xml";
sfd.Filter =“ XML文件( .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: 输出:
Try changing .xml
to .bin
. 尝试将
.xml
更改为.bin
。 That should fix your problem 那应该解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.