Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
I am trying to update/write to a node in an XML. I have the acception of 'The process cannot access the file because it is being used by another process'. when I googled it they say try using(..){} I did try and also I tried to change the file share mode to 'readwrite' or shut down the antivirus program taht is currently running but still I couldnt find a solution to it. I am getting the error while I am trying to write the xml it throws that an error. The code is like this:

if (agService.Status == ServiceControllerStatus.Stopped)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Application.StartupPath + "\\ReviewRules.xml");
    XmlNodeList timerNodes = xmlDoc.SelectNodes("/Settings/Timer");
    foreach (XmlNode node in timerNodes)
    {
        node["Timer"].InnerText = TimeInterval;
    }
    StringWriter sw = new StringWriter();
    XmlTextWriter xw = new XmlTextWriter(sw);
    xmlDoc.WriteTo(xw);
    
    string xml = xmlDoc.InnerXml.ToString();
    //xmlDoc.Save(Application.StartupPath + "\\ReviewRules.xml");
    //FileStream fs = File.Create(Application.StartupPath + "\\ReviewXML\\ReviewRules.xml");
    //FileStream fs = new FileStream(Application.StartupPath + "\\ReviewRules.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);            
    //File.WriteAllText(Application.StartupPath + "\\ReviewRules.xml", xml);
    //fs.Close();
    using (FileStream fs = File.Create(Application.StartupPath + "\\ReviewRules.xml"))
    {
        File.WriteAllText(Application.StartupPath + "\\ReviewRules.xml", xml);
        fs.Close();
    }
Posted
Updated 15-Dec-10 9:48am
v2

Rereading your question, the problem is obvious. You are opening a file stream to the file, then you are using File.WriteAllText to write the file rather than using the file stream you just opened.
 
Share this answer
 
Comments
#realJSOP 15-Dec-10 17:21pm    
Yup, that's it.
Dalek Dave 15-Dec-10 18:28pm    
Good Answer
Sometimes, as you test your application (during the debugging process), you may inadvertantly fail to properly shut the app down (usually the result of a coding error). This will generate that error. Make sure that after being shut down, your app isn't still showing up in Task Manager.

You calso download ProcessExplorer. It will tell you what processes have files open:

http://technet.microsoft.com/en-us/sysinternals/bb896653[^]
 
Share this answer
 
v2
Comments
AspDotNetDev 15-Dec-10 16:03pm    
Check out my (new) answer. The OP is opening a file stream, then using File.WriteAllText rather than that file stream.
why not just use xmlDoc.Save(path) as in the commented out part?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900