c# Exception The process cannot access the file

前端 未结 5 1617
孤独总比滥情好
孤独总比滥情好 2021-01-13 15:21

I\'m getting an exception: The process cannot access the file.

Here\'s the code:

if (!Monitor.TryEnter(lockObject))
    return;
try
{
    watcher.Ena         


        
5条回答
  •  天涯浪人
    2021-01-13 15:44

    You are trying to write on "Filename" file that is already open in the try block.

    Edit 1:

    It seems the lock is set by the process that is saving the file. When convert() is fired, filesystem has still not finished to save the file. It happens expecially if you have a big xml. If you add a sleep just before trying to write the file, exception is not raised.

    This is a quick&dirty patch.

    If xml files are saved with an high frequency, you need to add some kind of lock to the xml file changed.

    Edit 2:

    Try also to remove watcher's event before doing stuff, and add again after everything is done, so you prevent multiple events to be fired. Not so sure that EnableRaisingEvents = false will work in the right way. See this post also:

    EnableRaisingEvents (enabling and disabling it)

    try
    {
        watcher.EnableRaisingEvents = false;
        //Edit2: Remove the watcher event
        watcher.Changed -= new FileSystemEventHandler(convert);
    
        try
        {
          XmlDocument xdoc = new XmlDocument();
          xdoc.Load(FileName);
        }
        catch (XmlException xe)
        {
          System.Threading.Thread.Sleep(1000);  //added this line
          using (StreamWriter w = File.AppendText(FileName))
          {
            Console.WriteLine(xe);
            w.WriteLine("");
            w.WriteLine("");
          }
        }
    }
    
    /*
       Here all xslt transform code
    */
    
        //Edit2: Add again the watcher event
        watcher.Changed += new FileSystemEventHandler(convert);
    }
    catch (Exception e)
    {
       Console.WriteLine("The process failed: {0}", e.ToString());
    }
    

提交回复
热议问题