I save particular object in external file like this:
public void SaveSettings(string SavedFilePath, object Class)
{
//open the stream to write the new file
using (Stream StreamFile = File.Open(SavedFilePath, FileMode.CreateNew))
{
//instantiate the binary formatter object
BinaryFormatter binformat = new BinaryFormatter();
//loop through all properties in input object
foreach (PropertyInfo prop in Class.GetType().GetProperties())
{
//if the property is serailizable then serialize it and write its name and value in external file
if (prop.PropertyType.IsSerializable)
binformat.Serialize(StreamFile, prop.GetValue(Class, null));
}
//close the stream
StreamFile.Close();
}
}
And then I load the same object back like this:
public void LoadSettings(string ConfigFile, object Class)
{
//open the stream to read the file
using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
{
//instantiate the binary formatter object
BinaryFormatter binformat = new BinaryFormatter();
//loop through all properties in input object
foreach (PropertyInfo prop in Class.GetType().GetProperties())
{
//if the property is serailizable then deserialize it and read its name and value, and write this in a memory object
if (prop.PropertyType.IsSerializable)
{
object objValue = binformat.Deserialize(StreamFile);
prop.SetValue(Class, objValue, null);
}
}
//close the stream
StreamFile.Close();
}
}
What I want to achieve is that if prior to loading, the number of properties in current object changes, then I want to count the number of serialized objects in stream and loop through them, and then map them to those in current object, rather than looping through the properties in current object. Is this possible?