0

(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
      {
        //???
      }
    }
  }
Community
  • 1
  • 1
Narges
  • 65
  • 2
  • 10
  • 1
    possible duplicate of [Is there a way to check if a file is in use?](http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use) – bobthedeveloper Apr 18 '14 at 15:54
  • I already read that post, my problem is with the waiting part which wasn't explained there. – Narges Apr 18 '14 at 15:57
  • You're not going to know how long the file will remain locked. It could remain locked forever for all you know. All you can do is periodically retry. How often you retry is a judgement call on your end. – Jon B Apr 18 '14 at 16:02
  • How about polling the directory every 60 seconds and try to move files which are older (last-write) than 60 seconds. If the move does not work, ignore it because it will be tried again at the the next polling interval. – Andrew Morton Apr 18 '14 at 16:07
  • Files may have different sizes. Some might take more than 60 seconds to complete and some in less than 1 second. I don't want to waste time. – Narges Apr 18 '14 at 16:14
  • Check the answer provided, it should work without having to have an active wait / manually polling the resource. – Saverio Terracciano Apr 18 '14 at 16:32

1 Answers1

1

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.

Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42