c# Exception The process cannot access the file

邮差的信 提交于 2019-12-01 06:38:30

In your try block you have opened the file. You need to close it.

XmlDocument xdoc = new XmlDocument();
xdoc.Load(FileName);

Follow this example.

http://msdn.microsoft.com/en-us/library/zcsyk915.aspx

It may be because of the watcher (then FileShare.ReadWrite is the important part).

Try:

XmlDocument xdoc = new XmlDocument();
FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
xdoc.Load(fs);
Draykos

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("</test>");
        w.WriteLine("</testwrapper>");
      }
    }
}

/*
   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());
}
user726720

The solution to this problem is right at this link:

Exception during xml processing

This was another question I raised. Thank you all of you who spent their time in helping me out.

Make sure the file does not exist.

I had to recreate my build configuration and the old file still existed. Once I deleted the old transform I was able to recreate the new transform.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!