0

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);
Ammar Ali
  • 77
  • 1
  • 3
  • 15
  • That is entirely normal. When you get the FSW event, the program that's updating the file is still actively using it. Having to wait until it is done with the file is almost always required. You cannot predict how long that takes. Put the path to the file in a list, use a timer to periodically try to get the file opened. – Hans Passant Oct 19 '14 at 10:55

1 Answers1

-1

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.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
  • I dropped files manually and I didn't get the error, I will wait for real time heavy messages flow and mark it as a resolved. many thanks – Ammar Ali Oct 19 '14 at 11:55
  • Try writing an small application or script that opens the file, waits a while, writes to it, and then closes it. It should help you debug. – Markus Jarderot Oct 19 '14 at 15:26