XML DOM save - File Permission denied

Hi, I'm trying to do the following:

// Get xml file
XmlTextReader myReader =new XmlTextReader(Server.MapPath("SiteStatus.xml"));

// Load XML doc
XmlDocument objXmlDoc =new XmlDocument();
objXmlDoc.Load(myReader);
myReader.Close();

// Set "status" attribute
XmlNode myNode = objXmlDoc.SelectSingleNode(@"//eTracker");
myNode.Attributes["status"].Value = "off";
objXmlDoc.Save(Server.MapPath("SiteStatus.xml"));

I get the below error:
Exception Details:System.IO.IOException: The process cannot access the file "C:\Inetpub\wwwroot\eTracker\SiteStatus.xml" because it is being used by another process.

Any ideas?
[1007 byte] By [Nirbho] at [2008-1-12]
# 1
Hi,

I tried the same code and the only thing I needed to change was the security settings for the virtual folder. The exception I got was System.UnauthorizedException.

This can be avoided by giving WRITE permission to the folder in which the XML file is placed in. If you are using IIS6 you would need to give WRITE permission to the IIS_WPG User. Once you add the permission, it should work.

Regards,
Vikram

Vikram at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 2
Are you closing the XmlTextReader? If not, you're going to wind up with the file being left open, which may be why you are seeing that error. Try something like:
// Get xml file
XmlTextReader myReader = null;

try
{
myReader = new XmlTextReader(Server.MapPath("SiteStatus.xml"));
//do stuff
}
finally
{
if (myReader != null) myReader.Close();
}

HTH

GerrardLindsay at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 3
Do you have any other applications on the box that either write to SiteStatus.xml or read from it?
Knuckles at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 4
I bet you have multiple ASP requests all trying to update the sitestatus.xml file at the same time. To resolve this you should surround this code with an Application.Lock() and Application.Unlock() to ensure this code is synchronized and only one page will try and update the sitestatus.xml file at a time. You can also use the "using" pattern for safely disposing of the XmlReader as follows:

XmlDocument objXmlDoc = new XmlDocument();
string path = Server.MapPath("SiteStatus.xml");
using (XmlTextReader myReader = new XmlTextReader(path))
{
objXmlDoc.Load(myReader);
}

ChrisLovett at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...

.NET Development

Site Classified