I have an issue whilst streaming to a file, I’m sure there is a simple solution but I’m struggling to find it! What I’m attempting to do is very straightforward, I’m getting the contents of a class and serializing them into XML and streaming them to a file. The code I’m using is:
ObservableCollection<RackItemViewModel> rackVMs = ProjectTree.GetTreeData();
XmlSerializer serializer = new XmlSerializer(typeof(RackItem));
using (TextWriter tw = new StreamWriter(filename, false))
{
foreach (RackItemViewModel VM in rackVMs)
serializer.Serialize(tw, VM.RackItem);
}
ProjectTree.GetTreeData() just returns the data to be serialized. If I run the program and save the data it all works as expected, the data is saved and can be read back with Deserialize. The problem I’m having is when I perform more than one save. If I save one set of data to one file and then another set of data to another file, the first file is correct but the second file is a concatenation of the first file and the second! It seems that either the stream or the XMLSerializer are not releasing their contents between saves. I’ve tried using writefile instead of Stream and I still get the same issue, I’ve also tried flushing and closing the stream but this has no effect. Needless to say if I close and restart the application between saves it all works fine.
Could anyone tell me what I’m doing wrong please?
I thought I’d tidy up this thread as I’ve managed to solve the problem. It turns out that it was nothing to do with the serializing or streaming of the data. The data buffer being written wasn’t fully releasing the data between writes. I was checking the View Model object which was OK but the object being written (RackItem), wasn’t following suite. Silly error on my part. Thanks for the suggestions.