title: C# Serializing datacontracts from file
body: <p>I have a list of Xml messages specifically DataContract messages that i record to a file. And i am trying to deserialize them from file one by one. I do not want to read the whole file into memory at once because i expect it to be very big.</p>
  
  <p>I have an implementation of this serialization and that works. I did this by serializing using a FileStream and reading the bytes and using regular expression to determine the end of element. Then taking the element and using DataContractSerializer to get the actual object.</p>
  
  <p>But i was told I should be using higher level code to do this task and it seems like that should be possible. I have the following code that i think should work but it doesn't.</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>The above code is fed with an input file containing something along the following lines:</p>
  
  <pre><code>&lt;MessageType&gt;....&lt;/MessageType&gt;
  &lt;MessageType&gt;....&lt;/MessageType&gt;
  &lt;MessageType&gt;....&lt;/MessageType&gt;
  </code></pre>
  
  <p>It appears that i can read and deserialize the first element correctly but after that it fails saying:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I have read somewhere that it is due to the way DataContractSerializer works with padded '\0''s to the end - but i couldn't figure out how to fix this problem when reading from a stream without figuring out the end of MessageType tag in some other way. Is there another Serialization class that i should be using? or perhaps a way around this problem?</p>
  
  <p>Thanks!</p>