[英]How do I save a custom class to user settings using ApplicationSettingsBase?
[英]How to reload different objects by applicationsettingsbase?
// TestASettingsString and TestBSettingsString are byte[]
// TestASettings and TestBSettings are two objects to be saved
在SettingsSaving中,将TestASettings和TestBSettings序列化为两个单独的字节数组,然后保存(在某些其他函数中)
我的问题是如何从loadavedsettings中的TestASettingsString和TestASettingsString中分别恢复TestASettings和TestBSettings?
那就是我做formatter.Deserialize(stream);的时候。
如何将两个完全不同的对象TestASettings和TestBSettings与formatter.Deserialize(stream)分开?
谢谢
private void SettingsSaving(object sender, CancelEventArgs e)
{
try
{
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, TestASettings);
// TestASettingsString and TestBSettingsString are byte[]
TestASettingsString = stream.ToArray();
stream.Flush();
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
stream.Close();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private void LoadSavedSettings()
{
Reload();
// how to get TestASettings and TestBSettings from TestASettingsString and
// TestASettingsString seperately?
}
我怀疑部分问题在这里:
TestASettingsString = stream.ToArray();
stream.Flush();
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
对于MemoryStream
, Flush()
是无操作的。 您实际上是说:
TestASettingsString = stream.ToArray();
stream.SetLength(0);
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
哪个将重置流,将TestBSettingsString
作为单独的数据块提供? 当前, TestBSettingsString
实际上包含TestASettings
和TestBSettings
。
完成此操作后,应该只是扭转情况:
using(MemoryStream ms = new MemoryStream(TestASettingsString)) {
BinaryFormatter bf = new BinaryFormatter();
TestASettings = (WhateverType)bf.Deserialize(ms);
}
using(MemoryStream ms = new MemoryStream(TestBSettingsString)) {
BinaryFormatter bf = new BinaryFormatter();
TestBSettings = (WhateverOtherType)bf.Deserialize(ms);
}
另请注意:我建议不要使用BinaryFormatter
持久存储任何离线内容(磁盘,数据库等)。
反序列化它们需要如下代码:
var ms = new MemoryStream(TestASettingsString);
var fmt = new BinaryFormatter();
TestASettings = (TestAClass)fmt.Deserialize(ms);
其中,TestAClass是TestASettings的类型。 您需要在序列化代码中重置流,将Position设置回0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.