c# - save xml file using streamwriter -
i trying find way save data xml file encoding "iso-8859-7".
firstly loading xml using
public xmldocument loaddocument(string x) { xmldocument document = new xmldocument(); streamreader stream = new streamreader(xml, encoding.getencoding("iso-8859-7")); document.load(stream); return (document); }
to load attributes inside form controls , when save button clicked
private void savebtn_click(object sender, eventargs e) { xmlnodelist attributes = commonmethods.loaddocument(xml).documentelement.selectnodes("//class[@name='" + classname + "']/property[@id='" + id + "']/attribute::*"); (int x = 0; x < attributes.count; ) { foreach (control ctr in table1.controls) { if (ctr textbox) { if (ctr.text == attributes[x].value.tostring()) { x++; } else { attributes[x].value = ctr.text; commonmethods.savedocument(xml); x++; } } else if (ctr combobox) { if (((combobox)ctr).text == attributes[x].value) { x++; } else { attributes[x].value = ((combobox)ctr).text; commonmethods.savedocument(xml); x++; } } } } }
it saves changes xml file. used save without using xmlwriter xmldoc.save("sample.xml)
because of characters inside file had use different approach like.
public xmldocument savedocument(string x) { xmldocument document = new xmldocument(); streamwriter stream = new streamwriter(x,false,encoding.getencoding("iso-8859-7")); document.save(xml); return (document); }
the problem when compile says "xml used process" , fails.
system.io.ioexception
you've got exception because file still opened streamreader pending finalization (garbage collection). should dispose streams (and reader / writers) release file handle possible.
public xmldocument loaddocument(string path) { xmldocument document = new xmldocument(); using (streamreader stream = new streamreader(path, encoding.getencoding("iso-8859-7"))) { document.load(stream); } return (document); } public xmldocument savedocument(xmldocument document, string path) { using (streamwriter stream = new streamwriter(path,false,encoding.getencoding("iso-8859-7"))) { document.save(stream); } return (document); } private void savebtn_click(object sender, eventargs e) { var doc = commonmethods.loaddocument(xml); xmlnodelist attributes = doc.documentelement.selectnodes("//class[@name='" + classname + "']/property[@id='" + id + "']/attribute::*"); (int x = 0; x < attributes.count; ) { foreach (control ctr in table1.controls) { if (ctr textbox) { if (ctr.text == attributes[x].value.tostring()) { x++; } else { attributes[x].value = ctr.text; commonmethods.savedocument(doc, xml); x++; } } else if (ctr combobox) { if (((combobox)ctr).text == attributes[x].value) { x++; } else { attributes[x].value = ((combobox)ctr).text; commonmethods.savedocument(doc, xml); x++; } } } } }
Comments
Post a Comment