我在为可观察的联系人对象集合创建二进制序列化时遇到问题。 Person对象包含firstname,lastname和age属性。 该集合称为 NewAccountList 。
我希望能够通过将收藏数据保存到文件中来保存它。当单击保存按钮时,此操作当前发生,但它执行xml序列化而不是二进制序列化。
private void MenuItem_Click_2(对象发件人,RoutedEventArgs e) { //创建OpenFileDialog Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection)); 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
{}
}
有人能给我一个如何保存对象集合的好例子吗?
答案 0 :(得分:1)
完整代码示例
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);
}
}
}
}
输出:
答案 1 :(得分:0)
尝试将.xml
更改为.bin
。这应该可以解决你的问题