0

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?

Codey
  • 487
  • 1
  • 8
  • 27
  • you can use a temporary file – styx Mar 27 '19 at 14:56
  • The file should be opened by party which writes to the file with appropriate [`FileShare`](https://learn.microsoft.com/ru-ru/dotnet/api/system.io.fileshare?view=netframework-4.7.2) mode in order to allow subsequent file openings. – Dmytro Mukalov Mar 27 '19 at 14:56

0 Answers0