How to save and load the contents of a multiline textbox to XML?
I have a multiline textbox, and I use databinding to bind its Text property to a string. This appears to work, but upon loading the string from XML, the returns (new lines) get lost. When I inspect the XML, the returns are there, but once the string is loaded from XML they are lost. Does anybody know why this is happening and how to do this right.
(I am not bound to use either a multiline textbox, or a string property for binding, I just a maintainable, (and preferably elegant) solution. )
Edit: Basically, I use the XmlSerializer class:
loading:
using (StreamReader streamReader = new StreamReader(fileName))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(streamReader);
}
saving:
using (StreamWriter streamWriter = new StreamWriter(fileName))
{
Type t = typeof(T);
XmlSerializer xmlSerializer = new XmlSerializer(t);
xmlSerializer.Seriali开发者_开发技巧ze(streamWriter, data);
}
When looking inside the XML, it saves multiline textbox data like this:
<OverriddenComponent>
<overrideInformation>
<Comments>first rule
second rule
third rule</Comments>
</overrideInformation>
</OverriddenComponent>
But those breaks no longer get displayed after the data is loaded.
What are the actual codes for new lines ? 0x0A or 0x0D or both? I stumbled on a similar problem before. The characters from a string "got lost" because textbox "converted" them on its own (or didn't understand them). Basicly, your xml file may be encoded one way, and your textbox uses other encoding, or it is lost during reading from, or writing to, the file itself (your string may be "messed up" also during reading from/writing to file). So there are 3 places your string may be tampered with, without your knowledge:
- During writing to the file (take notice what encoding you use)
- During reading from the file
- When displaying your string in textbox.
My advice is that you should assign the text that you read from the file to another string (not bound) before you assign it to the bound one and use a debugger to check how it changes. This http://home2.paulschou.net/tools/xlate/ is a useful tool to check what exactly is in your strings.
When I encountered this problem in my application, I ended up using binary/hex values of characters to write/read, and then converting them back when I needed to display. But I had to use a lot of strange ASCII codes. Maybe there's an easier solution for you out there.
EDIT: or it may be just some xml-related thing. Maybe you should use some other character to replace line break when writing it to xml?
精彩评论