Narges
Narges

Reputation: 65

detecting that a file is currently being written to

(I know It's a common problem but I couldn't find an exact answer)

I need to write a windows service that monitors a directory, and upon the arrival of a file, opens it, parses the text, does something with it and moves it to another directory afterwards. I used IsFileLocked method mentioned in this post to find out if a file is still been written. My problem is that I don't know how much it takes for another party to complete writing into the file. I could wait a few seconds before opening the file but this is not a perfect solution since I don't know in which rate is the file written to and a few seconds may not suffice.

here's my code:

while (true)
  {
    var d = new DirectoryInfo(path);
    var files = d.GetFiles("*.txt").OrderBy(f => f);

    foreach (var file in files)
    {
      if (!IsFileLocked(file))
      {
        //process file
      }
      else
      {
        //???
      }
    }
  }

Upvotes: 0

Views: 584

Answers (1)

Saverio Terracciano
Saverio Terracciano

Reputation: 3915

I think you might use a FileSystemWatcher (more info about it here: http://msdn.microsoft.com/it-it/library/system.io.filesystemwatcher(v=vs.110).aspx ).

Specificially you could hook to the OnChanged event and after it raises you can check IsFileLocked to verify if it's still being written or not.

This strategy should avoid you to actively wait through polling.

Upvotes: 2

Related Questions