I have an XML file which I need to write to. I can successfully do so already using the following:
//Code to open the File
public void Open(string FileName, string FilePath)
{
try
{
XmlDoc = new XmlDocument();
XmlDoc.PreserveWhitespace = true;
XmlnsManager = new XmlNamespaceManager(mXmlDoc.NameTable);
XmlnsManager.AddNamespace("", "urn:xmldata-schema");
FileStream = new FileStream(@Path.Combine(FilePath, FileName),
FileMode.Open, FileAccess.ReadWrite);
XmlDoc.Load(FileStream);
}
catch (Exception inException)
{
MessageBox.Show(inException.ToString());
}
}
//Code to write to the file
public void SetValueByElementName(string Name, string Value)
{
try
{
XmlNode node = XmlDoc.SelectSingleNode("//" + inElementID, XmlnsManager);
node.InnerText = Value;
}
catch (Exception inException)
{
MessageBox.Show(inException.ToString());
}
}
//Code to save the file
public void Save()
{
try
{
XmlDoc.Save(@Path.Combine(XmlFilePath, XmlFileName));
IsFileModified = false;
}
catch (Exception inException)
{
MessageBox.Show(inException.ToString());
}
}
However, the implementation of this class, is that every time I need to write something into the XML file, I have to save it. Now, I was told that I have to change this, and what should happen is that I have to save it only once which is at the end when reading/writing is done. How can I achieve this?
EDIT:
I forgot to add this: One thing I don't quite understand is that the implementation requires to close the file stream immediately.
//Code to close stream
private void CloseStream()
{
try
{
FileStream.Close();
}
catch (Exception inException)
{
MessageBox.Show(inException.ToString());
}
}
The flow is as follows:
- OpenFile (then immediately close it)
- CloseFile
- SetFirstElementValueByElementId (change something in the xml file).
- SaveFile (has to be called everytime I make changes, otherwise they won't reflect on the file).