Click here to Skip to main content
15,886,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have serialized my object to write to a file:

public void writeConfig()
{
	StreamWriter write = new StreamWriter(@"C:\users\public\documents\_myConfig.xml");
	XmlSerializer serialObject = new XmlSerializer(typeof(myObject));

	serialObject.Serialize(write, this);
	write.Close();

}


It works fine. Then I use Deserialize to read the file:

public void readConfig()
{
	StreamReader read = new StreamReader(@"C:\users\public\documents\_myConfig.xml");
	XmlSerializer serialObject = new XmlSerializer(typeof(myObject));
	SurveyConfig deSerialObject = (myObject)serialObject.Deserialize(read);
	read.Close();

}


What I have tried:

I don't think I'm doing this correctly because I have to do a deep copy to get the deSerialObject members in to myObject. Seems like that defeats the purpose. What am I missing? I am using a Singleton instance of my object...
Posted
Updated 2-Dec-19 18:49pm
v2
Comments
Maciej Los 2-Dec-19 15:10pm    
You have to show us how you have declared myObject...
It's very important!

Maybe you can try binary serialization, see answer here: c# - What are the differences between the XmlSerializer and BinaryFormatter - Stack Overflow[^]

As you can see in the diagram, under Binary formatter "(deep serialization)" is mentioned.
 
Share this answer
 
v2
Comments
Member 14576893 2-Dec-19 19:52pm    
Thank you. I looked into shallow vs. deep copy. It's a very simple object with just a few fields for configuration on app startup. Doing a shallow copy of the object seems to work for now.
RickZeeland 3-Dec-19 2:12am    
Forgot to mention that in normal POCO classes fields will not serialize, you have to use properties. But you seem to have already solved the problem :)
serialize in this way and it works

var xmlSerializer = new XmlSerializer(typeof(myObject));
           using (var xmlStream = new MemoryStream())
           {
               xmlSerializer.Serialize(xmlStream, root);
               xmlStream.Position = 0;
               var xmlDoc = new XmlDocument();
               xmlDoc.Load(xmlStream);
               xmlDoc.Save(@"C:\users\public\documents\_myConfig.xml");
           }


using(StreamReader read = new StreamReader(@"C:\users\public\documents\_myConfig.xml"))
{
	myObject deSerialObject = (myObject)serialObject.Deserialize(read);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900