XmlSerializer.Deserialize(Stream s) Strips \r out of \r\n !

I encountered a bug recently on one of the projects that i am working on. basicaly the program was getting user input through a text box(after wich all the user data gets saved as a object’s properties…) and then seriallizing it to XML and writing it to a DB. afterwards when the user wants to view this data the program would read it off the DB and deserialize the XML string to a object, that can be reprecented to the user.

when the user hit return in the text box to get to a new line it would result in ‘\r\n’ which represents a both carriege return and a new line. now when this data gets serialized, it goes in to the DB as it should. everything is fine until then. but when you try to deserialize this data that includes ‘\r\n’ using XmlSerializer.Deserialize(Stream s), it would strip the ‘\r’ out of every place where you have ‘\r\n’. this made my text boxes display some unreadable chars! this is happening because of the way XmlSerializer.Deserialize(Stream s) works. more details here(this is the page that solved my problem and teached me most of the stuff i am writing here :D ).

a quick solution would be to use something like this…

XmlSerializer.Deserialize(new XmlTextReader(Stream s))

here when you create a XmlTextReader, its XmlTextReaderproperty is by default set to false. but when you use the above mentioned XmlSerializer.Deserialize(Stream s) overload, it internally create a XmlTextReader and sets it’s XmlTextReader to true. which causes the ‘Bug’.

hope this will save some of your/my time in the feutre.

2 Responses to “XmlSerializer.Deserialize(Stream s) Strips \r out of \r\n !”

  1. RNEELY Says:

    Wow thanks. This solution really helped.

  2. rython Says:

    I had the same problem. Your solution worked. Thank you very much!

Leave a Reply