I have a list of Xml messages, namely DataContract messages that I write to a file. And I'm trying to deserialize them from a file one by one. I do not want to read the entire file in memory immediately, because I expect it to be very large.
I have an implementation of this serialization and it works. I did this by serializing using a FileStream and reading bytes and using a regular expression to determine the end of the element. Then, taking the element and using the DataContractSerializer, you will get the actual object.
But I was told that I should use a higher level code to complete this task, and it seems that it should be possible. I have the following code, which I think should work, but it is not.
FileStream readStream = File.OpenRead(filename); DataContractSerializer ds = new DataContractSerializer(typeof(MessageType)); MessageType msg; while ((msg = (MessageType)ds.ReadObject(readStream)) != null) { Console.WriteLine("Test " + msg.Property1); }
In the above code, an input file is supplied containing something in the following lines:
<MessageType>....</MessageType> <MessageType>....</MessageType> <MessageType>....</MessageType>
It looks like I can read and deserialize the first element correctly, but after that it doesn't say:
System.Runtime.Serialization.SerializationException was unhandled Message=There was an error deserializing the object of type MessageType. The data at the root level is invalid. Line 1, position 1. Source=System.Runtime.Serialization
I read somewhere that this is due to the way the DataContractSerializer works with the augmented "\ 0" to the end - but I could not figure out how to fix this problem when reading from a stream without figuring out the end of the MessageType tag in another way. Is there another Serialization class that I should use? or perhaps a way to solve this problem?
Thanks!
source share