I have an application that must check a folder and read any files that are copied into it. How do I test if a file in that folder is currently being written to? I only want
When you open it with System.IO.File.OpenWrite(filename)
, it should throw IOException
.
So, in a try catch, the code being executed in the catch block should tell you the file was open.
Perhaps opening the file exclusively like this -
System.IO.File.Open(PathToFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
That could be placed in a loop with a try/catch until its successful.
Number of options. The one that springs to mind straight away is to try opening the file for write. If you raise an exception, it is still being written to. Wait for a defined period and try again.
Alternatively check the timestamps and only try reading the file 1 or 2 minutes after the timestamp last changed