Learn how to a build a cloud-first strategyRegister Now


How to check if file is locked

Posted on 2002-05-28
Medium Priority
Last Modified: 2012-05-04
Can anyone tell me how to check if a file is locked by an application for write access and how to check which user locked it?  Excel does this.  If you try to open a file already opened, it will tell you that the file is "locked for editing" by "...".

All I can do right now is to try to open the file and trap error number 70, "Permission denied".
Question by:ASP_Ray
  • 4
  • 3
  • 2
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7039421
As far as I know do the Office applications store the user into their files when opening the file...
LVL 16

Expert Comment

ID: 7040027
could you use an error handler?

Author Comment

ID: 7040414
I'm not sure what the comments from angelll and Richie Simonetti mean so let me restate my question.  I want to know how, from my program, to check if a file is locked by another program because the other program is editing the file.  If I could find out as well which user is using the application which locked the file, that would be nice too.  If you want, say, to delete a file, you must do more than just check if the file exists to avoid a run-time error.  You must also check if the file is locked.  Right now I'm using a workaround to check if the file is locked.  I try to open the file with the VB's Open statement and then check for error number 70.  I do it as follows:

  On Error Resume Next
  iFileNumber = FreeFile
  Open sFileSpec For Input As iFileNumber
  If Err.Number = 70 Then
    'Permission to open is denied
    MsgBox Err.Description
  End If
  Close iFileNumber

Actually, in practice, you would check
"If Err.Number <> 0" but this code is to illustrate what I mean.  

My previous comment about Excel is this.  If you try to open an Excel file on a server, if that file is already opened anywhere on the network, Excel will tell you that the file is locked and will tell you which usere is using the application which locked the file.  Don't get hung up on Excel though, I just used this as an example of ultimately what I would like to do.

Hope this clarifies thinks.  Please continue to comment.
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7041075
Hi ASP_Ray:
I did fully understand your problem, and even if you choose Excel as sample, it is a special case, as I know that Excel (as the other MS Office products) store the information of who has openend the file in the file itself, so that other Excel users can get notified of this when trying to open the same file.

This is not implemented for the mass of normal files, as no other application does store this information in their files...

So ultimately, you have to do the same way, either storing the information in the file itself or a secondary file besides... There is no way except checking the error as you showed, and using that method there is no way of telling who opened the file.


Author Comment

ID: 7044454
Thanks Angellll.  I'm sorry about the delay in answering but my ISP, MSN, was down all day yesterday.  

Now just one last clarification.  You already addressed it but I just want to emphasize.  Are you saying there is no direct way to check if a file is locked?  No Win32 API function?  I can only try to open the file and check for errors, which doesn't even directly return that the file is locked, just a general "permission denied"?
LVL 16

Accepted Solution

Richie_Simonetti earned 400 total points
ID: 7044929
Could you try this?
'from MSDN:

HOWTO: Determine If a File Is Already Open
Last reviewed: August 1, 1997
Article ID: Q172240  
The information in this article applies to:
Microsoft Win32 Application Programming Interface (API) included with: - Microsoft Visual Basic Learning, Professional, and Enterprise Editions

     for Windows, version 5.0

You can open a file multiple times in different applications as long as one application does not have exclusive access to the file. There may be times when your application needs to have exclusive access to a file, and the application may need to determine whether it is already open. This article explains how to determine whether a file is already open. It also contains two versions of a function you can use to detect whether a file is already open.

The only sure way your application can determine whether it can open a file exclusively is by trying to open the file. If you are able to open the file, your application has exclusive access. Otherwise, it doesn't.

If your application needs to determine whether a file is already open, it should attempt to open the file for exclusive-sharing access. If a sharing violation occurs during the attempt, the file is already open. If the attempt causes a different error, such as access denied or file not found, then your application will not be able to tell whether the file is already open.

The function described here is called IsFileAlreadyOpen, declared as:

   BOOL IsFileAlreadyOpen(char *filename); // In C/C++...
   Function IsFileAlreadyOpen(Filename As String) As BOOLEAN // In VB...

If this function returns TRUE, then the file is already open. It determines that the file is already open only if it gets ERROR_SHARING_VIOLATION when it attempts to open the file.
It will return FALSE in the following conditions:

The file is not already open.
The calling application does not have access to the file due to NTFS security.
The file does not exist.

You should check if the file exists before calling the function to eliminate the possibility of the latter condition.

Sample Code: C/C++ version of IsFileAlreadyOpen

   BOOL IsFileAlreadyOpen(char *filename)
      HFILE theFile = HFILE_ERROR;
      DWORD lastErr  = NO_ERROR;

      // Attempt to open the file exclusively.
      theFile = _lopen(filename, OF_READ | OF_SHARE_EXCLUSIVE);

      if (theFile == HFILE_ERROR)
         // Save last error...
         lastErr = GetLastError();
         // If the open was successful, close the file.

      // Return TRUE if there is a sharing-violation.
      return ((theFile == HFILE_ERROR) &&
              (lastErr == ERROR_SHARING_VIOLATION));

Sample Code: Microsoft Visual Basic version of IsFileAlreadyOpen

   ' Declaration for APIs used by our function...
   Private Declare Function lopen Lib "kernel32" Alias "_lopen" (ByVal
   lpPathName As String, ByVal iReadWrite As Long) As Long
   Private Declare Function GetLastError Lib "kernel32" () As Long
   Private Declare Function lclose Lib "kernel32" Alias "_lclose" (ByVal
   hFile As Long) As Long

   ' Our Function...
   Function IsFileAlreadyOpen(Filename As String) As Boolean
      Dim hFile As Long
      Dim lastErr As Long

      ' Initialize file handle and error variable.
      hFile = -1
      lastErr = 0

      ' Open for for read and exclusive sharing.
      hFile = lopen(Filename, &H10)

      ' If we couldn't open the file, get the last error.
      If hFile = -1 Then
         lastErr = Err.LastDllError
      ' Make sure we close the file on success.
         lclose (hFile)
      End If

      ' Check for sharing violation error.
      If (hFile = -1) And (lastErr = 32) Then
         IsFileAlreadyOpen = True
         IsFileAlreadyOpen = False
      End If

   End Function


Author Comment

ID: 7065815
Thanks for all the comments guys, especially you Angelll.  Wish I could split the points with you but since I can't, code always beat no code.  Anyway, keep up the good work guys.
LVL 16

Expert Comment

ID: 7065820
Thanks for "A" grade but what could you use, Angel's suggestion or mine?, i don't understand.

Author Comment

ID: 7071276
Riche, Angel's suggestion was very informative.  It addressed that only office products could tell which user locked the file.  But my primary concern was how to check that file was locked (you can read the question again), and my method, it seemed to me at the time, was only only a work-around.  I wanted a definitive method to do that.  You provided code for this, and even more that, you provided an explanation that had the authority of Microsoft.  That is why I gave you the grade A.  I am now using the code you provided.

Actually I searched the MSDN library for hours on that subject, but I never searched for "sharing violation" or anything similer.  I was searching for text like "locked" etc. so I never came across that article.  Thanks again Richie and lots of thanks to Angellll as well.  Angellll taught me something I am glad to know and you gave me code I am now using.

PS.  I just re-read the last comment I made and I guess since it only spoke to Angelll specifically, you might have thought I was using his suggestion.  SORRY for the confusion.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question