0

So I am doing this:

public MainWindow()
{
    InitializeComponent();

    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = "F:\\Scoreboard Assistant\\output\\";
    watcher.Filter = "event.xml";
    watcher.NotifyFilter=NotifyFilters.LastWrite;
    watcher.Changed += new FileSystemEventHandler(file_Changed);
    watcher.EnableRaisingEvents = true;
}

private void file_Changed(object sender, FileSystemEventArgs e)
{
    XmlDocument config = new XmlDocument();
    config.Load(e.FullPath.ToString());
    string text1 = config.SelectSingleNode("event/text1").InnerText;
    string text2 = config.SelectSingleNode("event/text2").InnerText;
}

What I am doing is watching for changes to a specific XML file. Then if a change to the file is detected, it will read the XML file and extract variables from it. However, when I run the code, I get the following error:

An unhandled exception of type 'System.IO.IOException' occurred in System.Xml.dll

Additional information: The process cannot access the file 'F:\Scoreboard Assistant\output\event.xml' because it is being used by another process.

How do I fix this?

1 Answer 1

1

FileSystemWatcher can raise multiple write events while the file is written. In fact, it will raise an event per buffer flush. This error means some other process wrote to the file, but did not finish yet.

How do you handle this? Simply ignore this error and try again on the next write event you receive. You may see several write events where the file is locked, but by the time you receive the last event it should have been unlocked by the other process.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't realize that the changed event would get fired so many times. Putting my code into an empty try-catch fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.