I have some archive file with data, I have some thread that writes to this archive file, at the main thread I have file system watcher that reads the file content when there is some change:
static FileSystemWatcher watcher = new FileSystemWatcher();
string archPath=@"C:\arch.xml";
public MyClass()
{
watcher.Path = dir;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime;
watcher.Filter = Path.GetFileName("*" + archPath);
watcher.Changed += OnFileChanged;
watcher.Created += OnFileCraeted;
watcher.EnableRaisingEvents = true;
}
public void OnFileChanged(object source, FileSystemEventArgs e)
{
try
{
watcher.EnableRaisingEvents = false;
LoadArchive();
}
finally
{
watcher.EnableRaisingEvents = true;
}
}
void LoadArchive()
{
DataSet ds = new DataSet();
ds.ReadXml(archPath); /// <----this line throws exeption
}
System.IO.IOException: The process cannot access the file 'C:\arch.xml' because it is being used by another process.
my question: I want to read the content when there is some change, how to avoid this exeption?