If you want to append to the same file, just use the same TextWriter and close it when you're done:
XmlSerializer xmlSel = new XmlSerializer(typeof(Foo));
TextWriter txtStream = new StreamWriter("xmlStreamFile.xml");
for (int i = 1; i <= 3; i++)
{
Foo foo = new Foo(i * 100);
xmlSel.Serialize(txtStream, foo);
Console.WriteLine("Serialize done #" + i);
txtStream.Flush();
}
txtStream.Close();
txtStream.Dispose();
In this sample Foo
is just a simple struct, but it would work with your class as well.
Edit: assuming you're using WinForms you can have the XmlSerializer and StreamWriter members of the class itself:
class Form1 : Form
{
private XmlSerializer xmlSel = null;
TextWriter txtStream = null;
//....
}
Then in the button click method initialize them once if null and serialize what you need:
if (xmlSel == null)
{
xmlSel = new XmlSerializer(typeof(Foo));
txtStream = new StreamWriter("xmlStreamFile.xml");
}
xmlSel.Serialize(txtStream, foo);
txtStream.Flush();
And finally in the Form close event, close and dispose the writer:
txtStream.Close();
txtStream.Dispose();