My file watcher event read the first file only and then I get the following error: "Error: System.IO.IOException: The process cannot access the file 'D:\TREE\Dump\TF20141004011343313.txt' because it is being used by another process."
Here is my code:
int? msgID;
string dup ="";
try
{
//---------read from file------------
string block;
using (StreamReader sr = File.OpenText(MsgsPath + "\\" + e.Name))
{
block = sr.ReadToEnd();
}
and "using" should handle the open and close automatically, right? I then use this code to move processed files:
File.Move(MsgsPath + "\\" + e.Name, MsgsPath + "\\Archive\\" + e.Name);
The FileSystemWatcher
Created
event is triggered as soon as the other process opens the file for writing. Following that, one or more Changed
events will follow, when other process writes to the file, and finally closes it.
The easiest way to get around the error, would be to wait a short while before trying to access the file:
Thread.Sleep(500);
A more advanced method, is to wait a short while from the last Changed
event.