I created a ping application with a service that pings to URLs. The list of the URLs is stored in an XML file.
My application crashes when I’m trying to add a new site to my XML while the service is running.
VS2010 says my file is being used by some other process but I’m sure that everything is fine. My service isn’t using the XML while I’m adding to it.
BUT I guess using an XmlReader & XmlWriter at the same time is where it crashes.
I’ll rewrite my code with LINQ to XML but I was wondering if it’s possible to use XmlReader & XmlWriter at the same time?
private void saveSites(Site newSite)
{
XmlDocument XDoc = new XmlDocument();
bool fileExists = true;
if (File.Exists("c:\\temp\\sites.xml") == false)
{
createXML();
fileExists = false;
}
using (XmlReader XReader = XmlReader.Create("c:\\temp\\sites.xml"))
{
XDoc.Load(XReader);
if (fileExists == true)
{
XmlNode SiteNode = XDoc.CreateNode(XmlNodeType.Element, "site", "");
XmlNode URLNode = XDoc.CreateNode(XmlNodeType.Element, "url", "");
URLNode.InnerText = newSite.URL;
XmlNode EmailNode = XDoc.CreateNode(XmlNodeType.Element, "email", "");
EmailNode.InnerText = newSite.Email;
SiteNode.AppendChild(URLNode);
SiteNode.AppendChild(EmailNode);
XDoc.DocumentElement.AppendChild(SiteNode);
}
else
{
foreach (Site site in sites)
{
XmlNode SiteNode = XDoc.CreateNode(XmlNodeType.Element, "site", "");
XmlNode URLNode = XDoc.CreateNode(XmlNodeType.Element, "url", "");
URLNode.InnerText= site.URL;
XmlNode EmailNode = XDoc.CreateNode(XmlNodeType.Element, "email", "");
EmailNode.InnerText = site.Email;
SiteNode.AppendChild(URLNode);
SiteNode.AppendChild(EmailNode);
XDoc.DocumentElement.AppendChild(SiteNode);
}
}
XDoc.Save("c:\\temp\\sites.xml");
}
}
Your reader is blocking the writing because it is in the using block. I’d suggest using the Load method the XmlDocument object with a uri instead of creating your own reader. Then also you can separate the initilisation from the writing operation.