Wrestling to contain open files

Programmatically closing open files on a Windows server

Working on a recent project, I needed a process to automate the closing of open PDF files on a Windows Server. The server in question had a process which built, compiled and digitally signed PDF files based on certain database conditions and triggers. The PDF files were then stored in a folder structure based on the database key.

A problem arose when users of the system had opened the PDF and kept them open, holding a lock on the file. If the status of the database changed requiring a new version of the PDF to be built, the process failed because it couldn’t write to the file due to the lock.

Unfortunately, I didn’t have the luxury of time to refactor the system to account for this. A decision was made to forcibly close the open connections to the file in question so that the regeneration of the PDF would succeed.

Rather than developing new code, I decided to shell out of the program and use the openfiles command supplied as part of Windows.


openfiles /disconnect /op "pdftoclose.pdf" /id *

The /op switch is used to disconnect all open files with the supplied filename. The /id switch used with the wildcard (*) is used to disconnect all the files opened with the specified numeric open file id on the computer.