SharePoint Tip #17: Testing if an Office Document is Open

In a Document Library, when you create a new document using the New button (or edit one that already exists), SharePoint will open the proper client application (if it knows which one it is) for you to edit the file. If you have an event handler attached to the ItemAdded or ItemUpdated event, and you wish to update the list item inside that handler, you might not be allowed to do so because the client application is locking the file while it's being edited.

So, how do you check if the file is being locked by the client application?

The SPFile class has three properties that might help you with that:

SPFile.CheckOutStatus – this property indicates if and how the file has been checked-out. It has one of four possible values:

  • SPFile.SPCheckOutStatus.None – the file is not checked-out.
  • SPFile.SPCheckOutStatus.LongTerm – the file was checked-out using the SharePoint interface (or hasn't been checked-in yet).
  • SPFile.SPCheckOutStatus.LongTermOffline – the file was check-out for offline editing.
  • SPFile.SPCheckOutStatus.ShortTerm – the file is not checked-out in SharePoint, but is being locked by a client application.

SPFile.CheckOutDate – this property stores the date and time of the check-out (if applicable) in UTC date format.

SPFile.CheckOutExpires – this property stores the date and time when a Short Term Check-Out license expires, in UTC date format. This property can only be used if the CheckOutStatus value is ShortTerm.

To check whether a file is being locked by a client application, just test the SPFile.CheckOutStatus for the ShortTerm value. Additionally, you might want to know when it was checked-out (SPFile.CheckOutDate) and when will the short term check-out expire (SPFile.CheckOutExpires).

Notes:

  • The client application might not keep the file locked until the short term check-out expires, or it might renew the short term check-out license.
  • Word 2007, for instance, locks a file in 10 minute intervals (600 seconds).