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?
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.