How to reload different objects by applicationsettingsbase?
// TestASettingsString and TestBSettingsString are byte[]
// TestASettings and TestBSettings are two objects to be saved
In SettingsSaving, TestASettings and TestBSettings are serialized into two seperate byte arrays, and then saved (in some other function)
My question is how to recover TestASettings and TestBSettings from TestASettingsString and TestASettingsString seperately in loadsavedsettings?
That is when I do formatter.Deserialize(stream);
How to seperate two totally different objects TestASettings and TestBSettings from formatter.Deserialize(stream)?
Thanks
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 TestBSett开发者_运维问答ings from TestASettingsString and
// TestASettingsString seperately?
}
I suspect part of the problem is here:
TestASettingsString = stream.ToArray();
stream.Flush();
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
For MemoryStream
, Flush()
is a no-op. Do you actually mean:
TestASettingsString = stream.ToArray();
stream.SetLength(0);
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
which will reset the stream, giving TestBSettingsString
as a separate chunk of data? Currently TestBSettingsString
actually contains both TestASettings
and TestBSettings
.
With that done, it should just be a case of reversing things:
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);
}
Note also: I suggest not using BinaryFormatter
for persisting any thing offline (disk, database, etc).
Deserializing them requires code like this:
var ms = new MemoryStream(TestASettingsString);
var fmt = new BinaryFormatter();
TestASettings = (TestAClass)fmt.Deserialize(ms);
Where TestAClass is the type of TestASettings. You'll need to reset the stream in your serialization code, set the Position back to 0.
精彩评论