I am a beginner with .NET environment.
I have a windows application with three textboxes and one button. When the user clicks on the button, i want all the textbox values to be serialized in an XML format to a file.
I tried doing it this way,
DialogResult dr = new DialogResult();
private void button1_Click(object sender, EventArgs e)
{
AddCustomer customer = new AddCustomer();
customer.textBox1.Text = textBox1.Text;
customer.textBox2.Text = textBox2.Text;
customer.textBox3.Text = textBox3.Text;
customer.textBox4.Text = textBox4.Text;
saveFileDialog1.InitialDirectory = @"D:";
saveFileDialog1.Filter = "Xml Files | *.xml";
if (saveFileDialog1.ShowDialog().Equals(DialogResult.OK))
{
SerializeToXML(customer);
}
}
public void SerializeToXML(AddCustomer customer)
{
XmlSerializer serializer = new XmlSerializer(typeof(AddCustomer));
TextWriter textWriter = new StreamWriter(@"D:\customer.xml");
serializer.Serialize(textWriter, customer);
textWriter.Close();
}
this returned system.invalidoperationexception was unhandled exception
any ideas?
Thanks,
Michael
There are a lot of ways to write XML in .NET. Here is a way using
XmlWriterthat works for very simple content like in this case:One note: you should avoid doing file operations on the UI thread as this can result in blocking behavior (e.g. the disk can be slow and cause the UI to freeze up while it writes the file, or it could be writing to a network location and hang for a while as it connects). It is best to put up a progress dialog and display a message “Please wait while file is saved…” and do the file operation in the background; a simple way is to post the background operation the thread pool using
BeginInvoke/EndInvoke.If you want to use the XmlSerializer instead, then you would follow these steps:
publictype to act as the root element of your document and mark it withXmlRoot.publiccustom types which are also XML serializable, marking them withXmlElementorXmlAttributeas necessary.XmlSerializer.Serializewith an appropriateStream,StreamWriter, orXmlWriteralong with your root object.XmlSerializer.Deseralizewith an appropriateStream,TextReader, orXmlReader, casting the return type back to your root object.Full sample.
The type to serialize:
The code to read/write the data: