I’m writing a Windows service to process files created by another process over which I have no control. These files could potentially be very large (hundreds of megabytes).
I need to process and then delete the files after they’ve been created.
All the files will be written to a particular directory (by just a straight file copy as far as I’m aware), so I can just periodically iterate over the files in that directory, process them and then delete them.
What I’m worried about is what happens if my service queries the directory during the writing of a large file? Will the file show up to my service? Will it be locked so that I can’t get read access? Do I need to do anything special to check whether the file has finished copying, or can I just query File.Exists() or try to Open it with FileAccess.Read. How does Windows mark a file that is in the process of being copied?
If this was plain win32 you would try to open the file, with
CreateFile(), and a share mode that denied write access to others. That would have to fail if the other program was still writing the file since you can’t deny write access when the file is already opened with write access. If it succeeds, you know that the other process has finished.In .net you could, for example, create a
FileStreamusing one of the constructors that receives aFileShareparameter. This will ultimately map down to the underlyingCreateFile()API.