Search code examples
c#xmllinqfilesystemwatcher

Using FileSystemWatcher in detecting a xml file, using Linq in reading the xml file and prompt the results error "Root Element is Missing"


My application is already working it can detect the xml file and prompt the content of the xml file but sometimes it will prompt "Root element is missing", and sometimes also it is okay but when I open the xml file, it is ok, it has contents on it. How to solve this issue.

Here is the screenshot of the error:

enter image description here

Here is the code:

private void fileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        string invoice = "";
        using (var stream = System.IO.File.Open(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
        {
            var doc = System.Xml.Linq.XDocument.Load(stream);
            var transac = from r in doc.Descendants("Transaction")
                          select new
                          {
                              InvoiceNumber = r.Element("InvoiceNumber").Value,
                          };

            foreach (var i in transac)
            {
                invoice = i.InvoiceNumber;
            }
        }

        MessageBox.Show(invoice);
        fileSystemWatcher.EnableRaisingEvents = false;
    }

The error goes here var doc = System.Xml.Linq.XDocument.Load(stream);


Solution

  • The FileSystemWatcher will raise the event very quickly when the file chanes. It is possible that the write operatrion has not finished before you read the file.

    To test that, add a Thread.Sleep(100); before you read the file as a quick workaround.

    To get a better solution, do not open the file in shared mode, but try if you can open it exclusively. If this fails, wait some milliseconds and try again - until you can open the file exclusively. Also take care that the event might be triggered more than once - this depends on how the other task writes to the file.