The Way to Programming
The Way to Programming
I’m having some troubles serializing data in an XML-file using C#..
Basicly, I want to serialize data in a Linked List using the xmlSerializer:
Here’s what I have so far:
public void saveSudokuList()
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(head.GetType());
StreamWriter writer = new StreamWriter(@"C:\temp\sudoku.xml");
x.Serialize(writer.BaseStream, head);
}
“head” is my first node of the linked list, so I wanted to try it out with just one node first.
But, the program gives neither an error or an XML-file.
is there something I’m forgetting or missing?
And yes, this is for a project for school, but I’ve looked up serialization everywhere and nothing helps.
Same goes for the teachers, it’s a DIY-project, no help from school.
First thing: Is directory 'C:\temp' exist? If not, StreamWriter constructor will break execution of your function on line 2. You can catch that exception if you surround your code with try-catch block (that even recommended for I/O operations)
Second thing: You not close your stream. StreamWriter is buffered by default, meaning it won’t output until it receives a Flush() or Close() call.
So proper code should look something like this:
public void saveSudokuList()
{
try{
if(!Directory.Exists(@"C:\temp"))
Directory.CreateDirectory(@"C:\temp");
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(head.GetType());
StreamWriter writer = new StreamWriter(@"C:\temp\sudoku.xml");
x.Serialize(writer, head);
writer.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Last thing: Default serialization had some limitation, if above tips dont help, post code of ‘head’ object class.
Sign in to your account